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?