I have something like this:
Map<String, String> myMap = ...;
for(String key : myMap.keySet()) {
System.out.println(key);
System.out.println(myMap.get(key));
}
So is myMap.keySet()
called once in the foreach loop?
I think it is, but want your opinion.
I would like to know if using foreach in this way (myMap.keySet()
) has a performance impact or it is equivalent to this:
Set<String> keySet = myMap.keySet();
for (String key : keySet) {
...
}
The answer is in the Java Language Specification, not need to decompile :) This is what we can read about the enhanced for statement:
In your case,
myMap.keySet()
returns a subtype ofIterable
so your enhancedfor
statement is equivalent to the following basicfor
statement:And
myMap.keySet()
is thus called only once.I believe it's compiler optimized to run only once per loop entry.
It's only called once. In fact it uses an iterator to do the trick.
Furthermore, in your case, I think you should use
to avoid searching in the map each time.
keySet()
is called only once. The "enhanced for loop" is based on theIterable
interface, which it uses to obtain anIterator
, which is then used for the loop. It's not even possible to iterate over aSet
in any other way, since there is no index or anything by which you could obtain individual elements.However, what you really should do is abandon this kind of micro-optimization worries entirely - if you ever have real performance problems, the chance is about 99% that it's something you'd never thought about on your own.
Yes, it's called only once either way
If you want to be absolutely certain, then compile it both ways and decompile it and compare. I did this with the following source:
and when I decompiled the class file with Jad, I get:
So there's your answer. It is called once with either for-loop form.