我一直在尝试通过循环展开来优化一些极其性能关键的代码(一个快速排序算法,在蒙特卡罗模拟中被调用数百万次)。
这里是我试图加速的内部循环:
// Search for elements to swap.
while(myArray[++index1] < pivot) {}
while(pivot < myArray[--index2]) {}
我尝试将其展开为如下形式:
while(true) {
if(myArray[++index1] < pivot) break;
if(myArray[++index1] < pivot) break;
// More unrolling
}
while(true) {
if(pivot < myArray[--index2]) break;
if(pivot < myArray[--index2]) break;
// More unrolling
}
这完全没有任何影响,所以我改回了更易读的形式。我尝试过其他几次展开循环也有类似的经历。考虑到现代硬件上分支预测器的质量,展开循环什么时候仍然是一个有用的优化方法呢?