Reputation: 63104
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?
Upvotes: 2
Views: 145
Reputation: 1250
I do not think the JVM will optimize this read, but the overhead of the daload
operation should be insignificant.
If you want to read the value from the array only once, try assigning to a local variable (costing some trivial local variable stack memory)
int origVal = array[i];
int value1 = origVal;
...
int value2 = origVal;
Tests should prove that the change is arbitrary.
Upvotes: 0
Reputation: 45443
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.
Upvotes: 2