Marshall Farrier Marshall Farrier - 1 year ago 77
Java Question

Java for-loop best practice

What is the best way to loop through an array when you need the index?

Option 1:

int len = array.length;
for (int i = 0; i < len; ++i) {
array[i] = foo(i);

Option 2:

for (int i = 0; i < array.length; i++) {
array[i] = foo(i);

Or, does it not matter? Or is there a better way to do it?
Just to point out the differences: In one case, the length of the array is evaluated as part of the test in the loop, although the compiler should normally optimize that.

Secondly, is
any different here from
? I definitely prefer
if it is C++ but am not sure for Java.

Dan Dan
Answer Source

i++ vs ++i does not matter in this particular case. While C masters will tell you to store array.length in a variable, modern optimizing compilers make that unnecessary in this case as long as the length does not change in the loop. If you're really concerned you can benchmark both, but since .length doesn't actually need to traverse the entire array each time you'll be OK.