Is there a performance difference between a for loop and a for-each loop?

前端 未结 16 1478
清歌不尽
清歌不尽 2020-11-22 10:38

What, if any, is the performance difference between the following two loops?

for (Object o: objectArrayList) {
    o.DoSomething();
}

and <

16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 11:16

    Well, performance impact is mostly insignificant, but isn't zero. If you look at JavaDoc of RandomAccess interface:

    As a rule of thumb, a List implementation should implement this interface if, for typical instances of the class, this loop:

    for (int i=0, n=list.size(); i < n; i++)
        list.get(i);
    

    runs faster than this loop:

    for (Iterator i=list.iterator(); i.hasNext();)
          i.next();
    

    And for-each loop is using version with iterator, so for ArrayList for example, for-each loop isn't fastest.

提交回复
热议问题