Java Tip: Optimization Technique for Lists

Java Tip: Optimization Technique for Lists

The default size for a Java ArrayList class is 10. When an ArrayList reaches its capacity maximum (10), it increases its capacity by approximately half. That is why an ArrayList takes more time if it is not initialized with the proper size. When you add objects to an ArrayList and it reaches its maximum capacity, it creates another, bigger array (with a capacity of approximately 15) and copies the previous and new objects into the new array.

Obviously, creating a new array and copying objects is costly to performance. So, the best approach is to initialize the ArrayList with a proper size. To do this, you use constructors or ensureCapacity(int capacity), which results in better performance.

For example, use this code if you expect your ArrayList to store around 3000 objects:

List<String> str = new ArrayList(3000)


Share the Post: