Basic Java Optimisation Hints

5. Use arrays [] for small collections of objects

LinkedList, Set, Map and TreeSet (java.util package) are all very convenient, but they aren't necessarily high performance.

Use a separate Iterator object, means more objects, chained method calls...

Casting and a slow runtime type check

For very small, simple collections of objects or primitive types you are much better to use arrays (6 - 8 objects).

In the java.util package you'll find a bunch of nice container classes for managing groups of objects. LinkedList, Set, Map and TreeSet are all very convenient, but they aren't necessarily high performance. To access the contents of these containers you typically use a separate Iterator object. That means more objects, chained method calls and other speed sapping overheads. Also, the containers all store their contents as type Object, which means casting and a slow runtime type check with each access. For very small, simple collections of objects or primitive types you are much better to use arrays.

It's important to emphasise that this is only true for small collections: say to a maximum of 6 - 8 objects. When you have a large number of objects a HashMap or some form of tree can be extremely efficient. Obviously you should analyse the complexity of your algorithm and choose a data structure which makes sense. But for small collections it will always be hard to beat an array.