0
\$\begingroup\$

I am making and there I am making a frequent use of java.util.ArrayList for enemies, coins and shots. Is there any other utility in libgdx better than this from the Performance point of view.

Further, I can get my things done using a for loop too.So, Which would be better to use. A FOR LOOP or an ITERATOR

\$\endgroup\$
1
  • 3
    \$\begingroup\$ I really would not worry about it. Java does a ton of optimizations when compiling. It really comes down more to your usage. If for loops are a bottle neck in your program reducing the number of loops may be a better idea. See stackoverflow.com/questions/2113216/… for details. \$\endgroup\$
    – mobo
    Commented Jun 19, 2013 at 14:28

1 Answer 1

2
\$\begingroup\$

The most generic answer is to leverage a profiler; and you generally don't want to worry about these sorts of decisions too much until you have evidence that they are the source of an actual performance issue in your game.

However, you can make some initial decisions about the choice of container and traversal method based on some information about the algorithmic properties of those containers. For example, if all you're going is traversing a collection in order over and over, an array is usually better than a linked list due to its improved cache coherency / locality of reference (arrays are contiguous; elements in a linked list may be spread out all over your address space unless you're using a pooling allocator for the elements).

Similarly, trivial iteration of an array via a for loop with an index is about as bare as you can get: it involves the minimum of overhead. Iterators usually require the construction of some object and related state (because they hold the iteration state within them). This means they have a very slight memory overhead and potential garbage-collection overhead (due to transient object allocation). But on balance, they allow you to pass the iteration state around to other interfaces -- generally provided that you don't modify the underlying container during the iteration, which can invalidate the object state.

In short, to best decide the data structure you need, and the interaction methods you should use with that structure, you should make sure you have a basic understanding of the algorithmic tradeoffs of your options and the context within your game where you're going to employ these structures. Beyond that, you should not stress out about it too much -- always aim for readable, clear code first. Then profile your game regularly and investigate actual bottlenecks as they arise.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .