Java – modern for loop for raw arrays

Is there a performance difference between for loops on the original array?

Undertake:

double[] doubleArray = new double[300000];


for (double var: doubleArray) 
   someComplexCalculation(var);

or

for ( int i = 0,y = doubleArray.length; i < y; i++)
   someComplexCalculation(doubleArray[i]);

test result

I'm actually analyzing:

Total timeused for modern loop= 13269ms
Total timeused for old loop   = 15370ms

So modern loops run faster, at least on my Mac OS X JVM 1.5

Solution

Your handwritten "old" form executes fewer instructions and may be faster, although you must configure the file under a given JIT compiler to determine The "new" form will certainly not be faster

If you see the disassembled code (compiled by sun's JDK 1.5), you will 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: }

So you can see that more local variables are used The assignment from doublearray to TMP in line 1 is "extra", but it does not occur in the loop and may not be measurable The assignment of VaR in line 3 is also additional If there is a difference in performance, it will be responsible

Line 1 seems unnecessary, but if the array is evaluated by method before entering the loop, its results are cached

That is, I will use the new form unless you need to use index variables for some operations At run time, the JIT compiler may optimize any performance differences, and the new form is clearer If you continue to "manual", you may miss future optimization Generally speaking, a good compiler can optimize "stupid" code, but stumble over "smart" code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>