2

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?

2
  • 2
    Can we assume you're asking about a HotSpot VM? Commented Feb 26, 2013 at 23:24
  • It's really a question about the Java memory model. The JVM vendor is irrelevant. In reality it will be Sun's Hotspot JVM. Commented Feb 26, 2013 at 23:28

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.