Search code examples
libgdx

libGDX Array class benefits


The javadoc of libGDX Array class says: A resizable, ordered or unordered array of objects. If unordered, this class avoids a memory copy when removing elements (the last element is moved to the removed element's position).
Is the elements removal improvement the only advantage of this class or there are others?
In other words - if I'm not planning to remove elements from my list at all can I live with ArrayList?


Solution

  • Array is actually not the only "replacement" of standard Java collection classes. There are many more like ObjectSet or IntIntMap. You can find all of them here.

    They are mostly optimized to avoid garbage collection as much as possible. They do this in many ways.

    One way is the one you already pointed out, by trying to avoid memory copies when possible, for example in case of a removal of an element in an Array.

    Furthermore they re-use the iterators. The standard java collections do not do this, which is why there will be a new Iterator being created every time you are iterating over the collection.

    Another way is the use of primitives, which avoids the creation of Objects due to autoboxing. IntIntMap for example has int keys and int values. The standard java HashMap<Integer, Integer> cannot deal with primitives which will result in many autoboxed int -> Integer.

    You should always try to stick to the libgdx classes whenever you can, especially on mobile devices. On desktop the garbage collector is usually so fast that you won't notice it, but even there it can result in ugly FPS-lags.