7

I'm profiling my android game and surprised to see that:

for(O o : myArrayList)
{
}

Creates a bunch of heap allocations.

Aside from using a numeric i++ for loop, is there a better way to get around this problem? Can I preallocate my iterators or something?

jmasterx
  • 52,639
  • 96
  • 311
  • 557
  • No, there's no performance penalty. Take a look on this [response][1] [1]: http://stackoverflow.com/questions/256859/is-there-a-performance-difference-between-a-for-loop-and-a-for-each-loop – Maxim Shoustin Nov 10 '12 at 20:03
  • 1
    I'm not concerned with performance, I just want to avoid the garbage collector in my game. – jmasterx Nov 10 '12 at 20:05

1 Answers1

4

This loop,

     for(O o : myArrayList)
     {
     }

gets converted to:

     for(Iterator<O> iter = myArrayList.iterator(); iter.hasNext(); )
     {
        O o = iter.next();
     }

So Iterator objects will be getting allocated on the heap, if you use this pattern.

If you write like:

     O o = null;
     for(Iterator<O> iter = myArrayList.iterator(); iter.hasNext(); )
     {
        o = iter.next();
     }

or

    O o = null;
    Iterator<O> iter = myArrayList.iterator();
    while(iter.hasNext()){
        o = iter.next();
    }  

then I think there will not be much of GC involvement in the iteration as its only involves assignment of existing object references.

Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
  • Will this still cause the GC to get called up a lot more than it should? That is what I want to prevent. – jmasterx Nov 10 '12 at 20:00
  • I think if you declare `O o;` outside the loop then every time it will just change the reference of `o` with elements of the list, which should be better. – Yogendra Singh Nov 10 '12 at 20:04
  • 1
    These objects (loop iterators) will most probably exists only in the nursery and will never contribute to a major GC collection. – David Soroko Nov 10 '12 at 20:18