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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With