Does java cache array length calculation in loops

1.8k views Asked by At

Lets say that i have an array which i would like to iterate over:

int[] someArray = {1,2,3,4}

for (int i = 0; i < someArray.length; i++) {

    // do stuff
}

Will this length of aray be caclulated with each iteration or it will be optimized to calculate it only once ?

Should i iterate arrays by calculating the length in advance and pass that to a loop ?

for (int i = 0, length = someArray.length; i < length ; i++) {

    // do stuff
}
3

There are 3 answers

2
Jon Skeet On BEST ANSWER

As always for performance: write the simplest code you can, and test it to see whether it performs well enough.

If you only need the element (and not the index) I would encourage you to use the enhanced-for loop:

for (int value : array) {
    ...
}

As per JLS 14.14.2 that's basically equivalent to your first piece of code, but the code only talks about what you're actually interested in.

But if you do need the index, and assuming you don't change array anywhere, I believe the JIT compiler will optimize the native code to only fetch the length once. Obtaining the length is an O(1) operation, as it's basically just a field within the array, but obviously it does involve hitting memory, so it's better for the eventual code to only do this once... but that doesn't mean that your code has to do this. Note that I wouldn't expect the Java compiler (javac) to perform this optimization - I'd expect the JIT to.

In fact, I believe a good JIT will actually see code such as:

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

and be able to optimize away the array bounds checks - it can recognize that if it accesses the same array object all the time, that can't possibly fail with an array bounds error, so it can avoid the check. It may be able to do the same thing for more "clever" code that fetches the length beforehand, but JIT optimizations often deliberately target very common code patterns (in order to get the biggest "bang for buck") and the above way of iterating over an array is very common.

0
Sagar Gandhi On

From JLS 7

10.7 Array Members

The members of an array type are all of the following: • The public final field length, which contains the number of components of the array. length may be positive or zero.

Coming back to your question,java doesn't recount the number of elements in array on array.length. It returns the value of public final int length, calculated during array creation.

1
Neeraj Jain On

As length is the member of Array So it is already been set when you create an Array , On Each iteration you are only accessing that property nothing else .

So either you access it like

    int myArrayLength=arr.length;
for(int i=0;i<myArrayLength;i++)

or like :

   for(int i=0;i<arr.length;i++)

There will be no measurable performance change .