Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java compiler optimize array index lookups?

Tags:

java

for (int i = 0; i < array.length; ++i) {
    // Do something referencing array[i]
    // Do another thing referencing array[i]
    ...
}

In code such as this, is it actually useful to set a variable like currentValue = array[i] and then reference that instead of array[i]? I feel like the compiler would be smart enough to do something like that and render such code pointless.

like image 640
755 Avatar asked Apr 07 '26 20:04

755


1 Answers

If you read the byte code that the compiler generates you will see that it does no such optimization. This means that in interpreted mode the array lookup will be done every time. If the method with the loop runs enough many times the JIT compiler will have another look at it and may optimize it.

Conclusion: if you want predictable results, store the array element in a local variable. More importantly, that way the code becomes more readable too.

like image 167
Joni Avatar answered Apr 09 '26 11:04

Joni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!