0

i wonder about performance of using method call as foreach argument for getting collection. Lets look at example:

for (Entry<K, V> entry : map.entrySet()) {
    doing.stuff();
}

I suppose that JVM will call map.entrySet() only once before starting loop, take first element, take his iterator and iterate over it, calling map.entrySet() never again, or in case of arrays just iterating over it with locally created int iterator (or sth like that), but I dont know how JVM works, so I'd like to be sure - does it work this way, or is better to save collection before loop and pass it as local var, instead of calling an getter inside loop ?

Fisher
  • 1,712
  • 1
  • 19
  • 38
  • 1
    See http://stackoverflow.com/questions/904582/java-foreach-efficiency?rq=1 –  Apr 23 '13 at 05:33
  • Refer this http://stackoverflow.com/questions/256859/is-there-a-performance-difference-between-a-for-loop-and-a-for-each-loop – prashant Apr 23 '13 at 05:33

2 Answers2

6

From Java Language Specification: The enhanced for statement:

The enhanced for statement has the form:

    for ( FormalParameter : Expression ) Statement

The enhanced for statement is equivalent to a basic for statement of the form:

    for (I #i = Expression.iterator(); #i.hasNext(); ) {
        VariableModifiersopt TargetType Identifier =
            (TargetType) #i.next();
        Statement
    }

Based on this, the map.entrySet() collection will be retrieved just once.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0
for(Object e : collection) {
}

is equivalent to

Iterator i = collection.iterator();
while(i.hasNext()) {
    Object e = i.next();
}

so it involves Iterator object creation. Besides Iterator.next() involves an extra check for concurrent modification. Thus in case of ArraList it may be more efficient to access elements by index

for(int i = 0; i < list.size(); i++) {
    Object e = list.get(i);
}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • The only problem with this approach is that if `list` is a `LinkedList` or another implementation of `List` that doesn't use an array the `get(int index)` method could traverse the whole list to get the last element. – Luiggi Mendoza Apr 23 '13 at 07:47