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

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

    By the variable name objectArrayList, I assume that is an instance of java.util.ArrayList. In that case, the performance difference would be unnoticeable.

    On the other hand, if it's an instance of java.util.LinkedList, the second approach will be much slower as the List#get(int) is an O(n) operation.

    So the first approach is always preferred unless the index is needed by the logic in the loop.

提交回复
热议问题