Does java cache the array reference in a for-loop?

Zee :

There are similar questions :

Advanced for loop does cache reference because it's using the same iterator instance : https://stackoverflow.com/a/29812538/4087512

Normal for loop does cache length : https://stackoverflow.com/a/1208331/4087512

But I'm trying to see if the reference is cached in a classic for-loop :

for(int i=0; i<someObject.getPrivateArray().length; i++){
    //do something where it's necessary to use i AND getPrivateArray()
}

as opposed to :

int j=0;
for(int var : someObject.getPrivateArray()){
    //do something with j & var
    j++;
}

From the question answered here : Is there a performance difference between a for loop and a for-each loop? these 2 would have the same performance on an array declared in a local scope, but will there be an overhead of fetching the array from a different object for the for-loop? It was answered above that the array is actually cached in the foreach loop.

AJNeufeld :

No.

Java has no way of knowing that someObject.getPrivateArray() will return the same object at each call. Therefore, it must call the function at each and every iteration.

Eg)

Queue<int[]> queue = ...;

for(int i=0; i<queue.remove().length; i++) {
    // ...
}

This is exactly the same pattern of code; only the names have changed, yet it is pretty clear the return value of queue.remove() won’t be cached.


Update

@MattTimmermans points out in a comment that the JVM could possibly in-line the someObject.getPrivateArray() call, so that the JVM might be able to determine the same object is being returned each time, and optimize away the call. This would require:

  • someObject be final or effectively final
  • getPrivateArray() be final, so it can be inlined
  • getPrivateArray() must be side-effect free (or the side effects must be executed anyway)
  • the returned value must be final so that some other entity can’t modify it, guaranteeing the same value is returned

In this case, the JVM might optimize the call away and move the fetch out of the loop, so effectively caching the result. I wouldn’t rely on it, when caching the value yourself is easy to do.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=144096&siteId=1