Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List iterator causes heap allocations?

Tags:

java

android

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?

like image 940
jmasterx Avatar asked Nov 10 '12 19:11

jmasterx


1 Answers

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.

like image 185
Yogendra Singh Avatar answered Oct 30 '22 04:10

Yogendra Singh