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

前端 未结 16 1560
清歌不尽
清歌不尽 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:19

    From Item 46 in Effective Java by Joshua Bloch :

    The for-each loop, introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely. The resulting idiom applies equally to collections and arrays:

    // The preferred idiom for iterating over collections and arrays
    for (Element e : elements) {
        doSomething(e);
    }
    

    When you see the colon (:), read it as “in.” Thus, the loop above reads as “for each element e in elements.” Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once. While you can do this by hand (Item 45), programmers don’t always do so.

提交回复
热议问题