In Java, does calling a field accessor in a loop create a new reference on each iteration of the loop?
Say I have a loop like
for (Foo aType : bar.getAList()) {
if (aType.getBaz().equals(baz)) {
return aType;
}
}
bar.getAList()
is called on each iteration of the loop. Does the JVM/compiler keep track of the fact that this is the same object, or does it naively call the method and create a refe开发者_开发技巧rence to the List each time?
Additionally, is this anything at all to worry about (recalling Jackson, Knuth, and Wulf's aphorisms regarding optimization)?
bar.getAList() isn't called in each iteration. The code is simplified into this during compilation :
for(Iterator<Foo> it = bar.getAList().iterator(); it.hasNext();){
Foo aType = it.next();
//...
}
Resources :
- oracle.com - The for-each loop
精彩评论