原始数组的现代 for 循环
原始数组上的 for 循环之间是否存在性能差异?
Is there any performance difference between the for loops on a primitive array?
假设:
double[] doubleArray = new double[300000];
for (double var: doubleArray)
someComplexCalculation(var);
或:
for ( int i = 0, y = doubleArray.length; i < y; i++)
someComplexCalculation(doubleArray[i]);
测试结果
我实际上分析了它:
Total timeused for modern loop= 13269ms
Total timeused for old loop = 15370ms
所以现代循环实际上运行得更快,至少在我的 Mac OSX JVM 1.5 上是这样.
So the modern loop actually runs faster, at least on my Mac OSX JVM 1.5.
推荐答案
您手写的旧"表单执行的指令更少,并且可能更快,尽管您必须在给定的 JIT 编译器下对其进行分析才能知道一定.新"形式肯定不更快.
Your hand-written, "old" form executes fewer instructions, and may be faster, although you'd have to profile it under a given JIT compiler to know for sure. The "new" form is definitely not faster.
如果您查看反汇编代码(由 Sun 的 JDK 1.5 编译),您会发现新"形式等同于以下代码:
If you look at the disassembled code (compiled by Sun's JDK 1.5), you'll see that the "new" form is equivalent to the following code:
1: double[] tmp = doubleArray;
2: for (int i = 0, y = tmp.length; i < y; i++) {
3: double var = tmp[i];
4: someComplexCalculation(var);
5: }
因此,您可以看到使用了更多的局部变量.在第 1 行将 doubleArray
分配给 tmp
是额外的",但它不会出现在循环中,并且可能无法测量.在第 3 行对 var
的赋值也是额外的.如果在性能上有差异,这将是负责任的.
So, you can see that more local variables are used. The assignment of doubleArray
to tmp
at line 1 is "extra", but it doesn't occur in the loop, and probably can't be measured. The assignment to var
at line 3 is also extra. If there is a difference in performance, this would be responsible.
第 1 行似乎没有必要,但如果数组是在进入循环之前由方法计算的,则缓存结果是样板.
Line 1 might seem unnecessary, but it's boilerplate to cache the result if the array is computed by a method before entering the loop.
也就是说,我会使用新形式,除非您需要对索引变量做一些事情.JIT 编译器可能会在运行时优化掉任何性能差异,并且新形式更加清晰.如果您继续手动"执行此操作,您可能会错过未来的优化.一般来说,一个好的编译器可以很好地优化愚蠢"的代码,但会绊倒聪明"的代码.
That said, I would use the new form, unless you need to do something with the index variable. Any performance difference is likely to be optimized away by the JIT compiler at runtime, and the new form is more clear. If you continue to do it "by hand", you may miss out on future optimizations. Generally, a good compiler can optimize "stupid" code well, but stumbles on "smart" code.
相关文章