Java cache array length calculation in loop

See English answer > what is the cost of calling array Length 8

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

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

    // do stuff
}

Will the length of this aray be recalculated with each iteration, or will it be optimized to be calculated only once?

Should I iterate the algebraic group and pass it to the loop by calculating the length in advance?

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

    // do stuff
}

Solution

As with performance: write the simplest code possible and test it to determine whether its performance is good enough

If you only need elements (not indexes), I recommend using the enhanced for loop:

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

According to JLS 14.14 2. It is basically the same as your first code, but the code only discusses what you are really interested in

But if you really need an index and assume that you haven't changed the array anywhere, I believe the JIT compiler will optimize the native code to get the length only once Getting length is an O (1) operation, because it is basically just a field in the array, but obviously it does involve hitting memory, so it is better for the final code to do it only once... But this does not mean that your code must do it Note that I don't want the java compiler (javac) to perform this optimization – I expect the JIT to do it

In fact, I believe a good jit will actually see the following code:

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

And it can optimize array boundary checking - it can recognize that if it always accesses the same array object, the array boundary error will not fail, so it can avoid checking For more "smart" code that can get the length in advance, it may do the same thing, but JIT optimization usually deliberately aims at very common code patterns (in order to get the maximum "buck") and the above iterative methods, which are very common on the array

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>