Does it calculate string length of java array in loops

Let's say that I have an array that 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 the aray be reset with every iteration or will it be optimized to be computed only once?

Should I iterate over the arrays, calculating the length ahead of time and passing that to the loop?

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

    // do stuff
}

      

+3


source to share


3 answers


As always for performance: Write the simplest code you can and test it to make sure it works well enough.

If you only want the element (not the index), then I would advise you to use an extended loop:

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

      

As of JLS 14.14.2 , which is basically equivalent to your first piece of code, but the code only says what you are really interested in.



But if you want the index, and if you don't change array

anywhere, I believe the JIT compiler will optimize native code to only fetch the length once. Getting the length is an O (1) operation as it is basically just a field within an array, but obviously it involves a memory grab, so it's better that the final code only does it once ... but that doesn't mean that your code should do this. Note that I did not expect the Java ( javac

) compiler to perform this optimization - I would have expected a JIT.

In fact, I believe that a good JIT will actually see the code, for example:

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

      

and be able to optimize the checking of array bounds - it can recognize that if it is accessing the same array object all the time, it cannot fail with an array bounds error, so it can avoid checking. It might be able to do the same for smarter code that picks up the length ahead of time, but JIT optimizations often target very common code patterns (to get the biggest dollar bang) and the aforementioned way of iterating over an array very often ...

+3


source


From JLS 7

10.7 Array Members



The elements of the array type are as follows: • A field public final

length

that contains the number of components in the array. length can be positive or zero.

Coming back to your question, java does not recalculate the number of elements in an array by array.length

. It returns the value public final int length

calculated during the creation of the array.

+5


source


How length

is a member Array

So, it is already set when creating the array, at each iteration you just get nothing from this property.

So either you refer to it like

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

      

or how:

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

      

The change in performance cannot be measured.

+3


source







All Articles