Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java foreach efficiency

Tags:

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) {    ... } 
like image 315
Flueras Bogdan Avatar asked May 24 '09 20:05

Flueras Bogdan


People also ask

Is forEach slower Java?

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.

Is forEach more efficient?

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.

Why forEach is faster than for loop in Java?

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.

Is forEach better than for loop Java?

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.


1 Answers

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.

like image 50
Eddie Avatar answered Oct 12 '22 14:10

Eddie