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

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

    Here is a brief analysis of the difference put out by the Android development team:

    https://www.youtube.com/watch?v=MZOf3pOAM6A

    The result is that there is a difference, and in very restrained environments with very large lists it could be a noticeable difference. In their testing, the for each loop took twice as long. However, their testing was over an arraylist of 400,000 integers. The actual difference per element in the array was 6 microseconds. I haven't tested and they didn't say, but I would expect the difference to be slightly larger using objects rather than primitives, but even still unless you are building library code where you have no idea the scale of what you will be asked to iterate over, I think the difference is not worth stressing about.

提交回复
热议问题