现代for循环的原始数组 [英] modern for loop for primitive array

查看:152
本文介绍了现代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]);

测试结果

我实际上对它进行了分析:

I actually profiled it:

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.

这篇关于现代for循环的原始数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆