On Java development, performance is an element that drives developers crazy. Small details can make a considerable difference. Especially when dealing with a big volume of data. One of these details is the kind of collection used to store data. Here it goes some tips on it.
It’s possible to define a list size when creating it. It’s useful if you know beforehand how many items it’ll have.
The default initial capacity of an
ArrayList is 16 items. For each newly added element, the capacity of the internal array is increased by one. It means a new array is created and all list elements are copied to it. Establishing the array initial capacity when knowing the size of the list is a good practice.
Even when a list will store less than 16 items, it’s better to pass that number to the constructor argument. This way you can save some memory. It’s not too much memory, but if this constructor is inside a loop, it can make a difference.
Another benefit of using
ArrayList instead of
LinkedList: one can retrieve any element by its index. Just like a native
Finally, we have implementations of collection based on hashes. They are fine to use with bigger groups of objects because they divide the group into subgroups. To find an element the algorithm identifies which subgroup contains a specific element. It does that using a hash calculated for every item. Then it restricts the search to that subgroup, instead of the whole collection.