Is there any performance difference between the for loops on a primitive array?
Assume:
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 actually profiled it:
Total timeused for modern loop= 13269ms Total timeused for old loop = 15370ms
So the modern loop actually runs faster, at least on my Mac OSX JVM 1.5.
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.
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:
So, you can see that more local variables are used. The assignment of
doubleArraytotmpat line 1 is ‘extra’, but it doesn’t occur in the loop, and probably can’t be measured. The assignment tovarat line 3 is also extra. If there is a difference in performance, this would be responsible.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.
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.