Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modern for loop for primitive array

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.

like image 686
Dan Avatar asked Nov 05 '08 20:11

Dan


People also ask

Can you use enhanced for loop on array?

Use the enhanced for each loop with arrays whenever you can, because it cuts down on errors. You can use it whenever you need to loop through all the elements of an array and don't need to know their index and don't need to change their values.

Can you use a for loop for an array?

We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.

Which loop is best with arrays?

The for loop is probably the most common and well known type of loop in any programming language. For can be used to iterate through the elements of an array: For can also be used to perform a fixed number of iterations: By default the increment is one.


1 Answers

My opinion is that you don't know and shouldn't guess. Trying to outsmart compilers these days is fruitless.

There have been times people learned "Patterns" that seemed to optimize some operation, but in the next version of Java those patterns were actually slower.

Always write it as clear as you possibly can and don't worry about optimization until you actually have some user spec in your hand and are failing to meet some requirement, and even then be very careful to run before and after tests to ensure that your "fix" actually improved it enough to make that requirement pass.

The compiler can do some amazing things that would really blow your socks off, and even if you make some test that iterates over some large range, it may perform completely differently if you have a smaller range or change what happens inside the loop.

Just in time compiling means it can occasionally outperform C, and there is no reason it can't outperform static assembly language in some cases (assembly can't determine beforehand that a call isn't required, Java can at times do just that.

To sum it up: the most value you can put into your code is to write it to be readable.

like image 71
Bill K Avatar answered Sep 30 '22 20:09

Bill K