javaperformanceloopsforeachpremature-optimization

Java foreach efficiency


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 I'd like to be sure.

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) {
   ...
}

Solution

  • 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.