List iterator causes heap allocations?

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.

链接地址: http://www.djcxy.com/p/66044.html

上一篇: 用行列标题读取CSV的Pythonic方法

下一篇: 列表迭代器会导致堆分配?