![](/img/trans.png)
[英]Why i += i + a[i++] + a[i++] + a[i++] results in 8?
[英]Why `a[i] = b; i++` perform better than `a[i++] = b`?
这些天,我正在用Java阅读DualPivotQuicksort算法的源代码。 我在代码中找到了一个有趣的注释。 它说:
/*
* Here and below we use "a[i] = b; i++;" instead
* of "a[i++] = b;" due to performance issue.
*/
a[less] = ak;
++less;
我只是不知道为什么。 有谁能够帮助我?
我决定比较每个选项的2 ^ 26个操作的执行时间。 我对此进行了4096次迭代,并获得了每个选项的平均值。
import java.util.ArrayList;
public class TestClass
{
public static void main (String[] args)
{
long startTime, endTime;
final int twoToPower26 = 67108864;
int[] a1 = new int[twoToPower26];
int[] a2 = new int[twoToPower26];
int i = 0;
int b = 1;
ArrayList<Long> optionATimes = new ArrayList<Long>();
ArrayList<Long> optionBTimes = new ArrayList<Long>();
for (int k = 0; k < 4096; k++)
{
i = 0;
//OPTION A: "a[i] = b; i++;"
startTime = System.currentTimeMillis();
while (i < twoToPower26)
{
a1[i] = b;
i++;
}
endTime = System.currentTimeMillis();
optionATimes.add(endTime - startTime);
i = 0;
//OPTION B: "a[i++] = b;"
startTime = System.currentTimeMillis();
while (i < twoToPower26)
{
a2[i++] = b;
}
endTime = System.currentTimeMillis();
optionBTimes.add(endTime - startTime);
System.out.println(k);
}
double averageTimeOptionA = calculateAverage(optionATimes);
double averageTimeOptionB = calculateAverage(optionBTimes);
System.out.println("OPTION A average time for 2^26 operations: " + averageTimeOptionA);
System.out.println("OPTION B average time for 2^26 operations: " + averageTimeOptionB);
}
public static double calculateAverage(ArrayList<Long> times) {
Long sum = (long) 0;
for (Long time : times) {
sum += time;
}
return sum.doubleValue() / times.size();
}
}
结果:
选项2 ^ 26操作的平均时间:105.9140625 ms
选项B 2 ^ 26操作的平均时间:105.846923828125 ms
在2 ^ 26次迭代中,每个选项的平均时间差异仅约67纳秒,在这种情况下,选项B的速度略快。
我觉得这几乎可以肯定地表明性能没有差异。 编译器很可能以相同的方式解释每个选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.