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

前端 未结 16 1488
清歌不尽
清歌不尽 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 10:59

    The for-each loop should generally be preferred. The "get" approach may be slower if the List implementation you are using does not support random access. For example, if a LinkedList is used, you would incur a traversal cost, whereas the for-each approach uses an iterator that keeps track of its position in the list. More information on the nuances of the for-each loop.

    I think the article is now here: new location

    The link shown here was dead.

提交回复
热议问题