Can the JVM optimize array reads when reading the same index multiple times? Consider the following:
public static void foo(int[] array) {
for (int i=0; i<array.length; i++) {
int value1 = array[i];
...
int value2 = array[i];
...
}
...
}
array[i]
is read twice in the loop. Assuming array[i]
is not reassigned in the loop, is the JVM allowed to assume that array[i]
did not change and thus read its value just once? Since array
is a passed-in mutable object, it could conceivably have changed between the first and second read.
I've looked the at the generated byte code and it does indeed read array[i]
twice (daload
). Is the JVM allowed to optimize this into one read?
Yes, the optimizer only considers single thread data flow, it doesn't care if a variable is changed by another thread, unless volatile/synchronized are involved.
Even if there's no optimization, the 2nd read should be really fast, around 1ns, since the data is most likely in L1 cache.