Java performance: arraylength vs iload

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

This will lead to code creation:

getstatic   #4;
arraylength

While the following code:

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

will be compiled as:

iload_3

Is there a difference between the two fragments? Which code is faster?

As you can see, the array is a static member in my case. Static and final, to be precise. Given the JIT optimization, the base optimizer can sense this and hardcode the length of the array into the machine code of the method. It is much more difficult to follow this logic using a local variable (the second case), so you might think that there is a greater likelihood that the first will be optimized than the second.

+3
source share
3 answers

, , , , . JIT-, , , .

, , , - , [0, length).

, JIT , , , , , .

, , .

+7

?

. arr , .

?

. , JIT, . , , - . , , , .

+1

JVM , , . .

However, some micro-optimization may confuse the JVM, and in the end you will get a slower optimized code.

The form I use when microoptimization

for (int i = 0, length = methodCall(arr); i < length; i++) {
   // use the array.
}

I prefer to use the simplest and most obvious solution to the problem, because the JVM is more likely to optimize this use case better.

+1
source

All Articles