Search code examples
javaandroiditeratorallocation

Preventing allocation for ArrayList iterators in Java


So I am part way through writing my first game on Android and after watching a lengthy presentation on optimising for games, I have been checking my allocations. I have managed to get rid of all in-game allocations apart from ones made my ArrayList when it creates an implicit iterator for the for(Object o : m_arrayList) convention.

There are a fair few of these iterations/allocations since all of my game objects, ai entities etc. are stored in these for their ease of use.

So what are my options?

  • I could, theoretically specify sensible upperbounds and use arrays, but I like the features of ArrayList such as exists and remove that keep code clean and simple.

  • Override ArrayList and provide my own implementation of iterator() that returns a class member rather than allocating a new iterator type each time it is used.

I would prefer to go for option 2 for ease of use, but I had a little go at this and ran into problems. Does anyone have an example of what I described in option 2 above? I was having problems inheriting from a generic class, type clashes apparently.

The second question to this then is are there any other options for avoiding these allocations?

And I guess as a bonus question, Does anyone know if ArrayList preallocates a number of memory slots for a certain amount (specified either in the ctor or as some shiftable value) and would never need to do any other allocations so long as you stay within those bounds? Even after a clear()?

Thanks in advance, sorry there is so much there but I think this information could be useful to a lot of people.


Solution

  • Use positional iteration.

    for ( int i = 0, n = arrayList.size( ); i < n; ++i )
    {
       Object val = arrayList.get( i );
    }
    

    That's how it was done before Java 5.

    For preallocation.

    ArrayList arrayList = new ArrayList( numSlots );
    

    or at runtime

    arrayList.ensureCapacity( numSlots );
    

    And for a bonus -> http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html