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

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

    It's weird that no one has mentioned the obvious - foreach allocates memory (in the form of an iterator), whereas a normal for loop does not allocate any memory. For games on Android, this is a problem, because it means that the garbage collector will run periodically. In a game you don't want the garbage collector to run... EVER. So don't use foreach loops in your draw (or render) method.

提交回复
热议问题