why is the enhanced for loop more efficient than the normal for loop

后端 未结 7 1735
一整个雨季
一整个雨季 2020-12-01 00:35

I read that the enhanced for loop is more efficient than the normal for loop here:

http://developer.android.com/guide/practices/performance.html#fo

相关标签:
7条回答
  • 2020-12-01 01:05

    It's a bit of an oversimplification to say that the enhanced for loop is more efficient. It can be, but in many cases it's almost exactly the same as an old-school loop.

    The first thing to note is that for collections the enhanced for loop uses an Iterator, so if you manually iterate over a collection using an Iterator then you should have pretty much the same performance than the enhanced for loop.

    One place where the enhanced for loop is faster than a naively implemented traditional loop is something like this:

    LinkedList<Object> list = ...;
    
    // Loop 1:
    int size = list.size();
    for (int i = 0; i<size; i++) {
       Object o = list.get(i);
       /// do stuff
    }
    
    // Loop 2:
    for (Object o : list) {
      // do stuff
    }
    
    // Loop 3:
    Iterator<Object> it = list.iterator();
    while (it.hasNext()) {
      Object o = it.next();
      // do stuff
    }
    

    In this case Loop 1 will be slower than both Loop 2 and Loop 3, because it will have to (partially) traverse the list in each iteration to find the element at position i. Loop 2 and 3, however will only ever step one element further in the list, due to the use of an Iterator. Loop 2 and 3 will also have pretty much the same performance since Loop 3 is pretty much exactly what the compiler will produce when you write the code in Loop 2.

    0 讨论(0)
提交回复
热议问题