for (int i=0; i<arr.length; i++) {
}
This will lead to code creation:
getstatic
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.
source
share