Reputation: 3091
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.
Upvotes: 3
Views: 236
Reputation: 111279
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.
Upvotes: 4