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) { ... }
As it turned out, FOREACH is faster on arrays than FOR with length chasing. On list structures, FOREACH is slower than FOR. The code looks better when using FOREACH, and modern processors allow using it. However, if you need to highly optimize your codebase, it is better to use FOR.
The foreach loop is considered to be much better in performance to that of the generic for loop. The foreach loop though iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively.
Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.
forEach() can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally.
If you want to be absolutely certain, then compile it both ways and decompile it and compare. I did this with the following source:
public void test() { Map<String, String> myMap = new HashMap<String, String>(); for (String key : myMap.keySet()) { System.out.println(key); System.out.println(myMap.get(key)); } Set<String> keySet = myMap.keySet(); for (String key : keySet) { System.out.println(key); System.out.println(myMap.get(key)); } }
and when I decompiled the class file with Jad, I get:
public void test() { Map myMap = new HashMap(); String key; for(Iterator iterator = myMap.keySet().iterator(); iterator.hasNext(); System.out.println((String)myMap.get(key))) { key = (String)iterator.next(); System.out.println(key); } Set keySet = myMap.keySet(); String key; for(Iterator iterator1 = keySet.iterator(); iterator1.hasNext(); System.out.println((String)myMap.get(key))) { key = (String)iterator1.next(); System.out.println(key); } }
So there's your answer. It is called once with either for-loop form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With