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

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

    foreach makes the intention of your code clearer and that is normally preferred over a very minor speed improvement - if any.

    Whenever I see an indexed loop I have to parse it a little longer to make sure it does what I think it does E.g. Does it start from zero, does it include or exclude the end point etc.?

    Most of my time seems to be spent reading code (that I wrote or someone else wrote) and clarity is almost always more important than performance. Its easy to dismiss performance these days because Hotspot does such an amazing job.

提交回复
热议问题