views:

49

answers:

1

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 reference to the List each time?

Additionally, is this anything at all to worry about (recalling Jackson, Knuth, and Wulf's aphorisms regarding optimization)?

+7  A: 

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 :

Colin Hebert
Excellent, that's exactly the information what I was looking for.
Feanor