Video in progress
How does the internal array of an ArrayList grow, and where does it show up on prod?
An empty ArrayList gets an array of size 10 on the first add, and when it fills up it grows by about 1.5x (old + old >> 1) and is copied with Arrays.copyOf. On large lists, these copies and having two arrays in memory at the same time increase allocation and GC pressure.
📖 Answer
new ArrayList<>() doesn't create an array right away; it points to a shared empty array. On the first add, 10 slots are allocated. After that: 10 → 15 → 22 → 33 → 49 → ...
Every growth allocates a new array and copies the old one over. The average add is still O(1) (amortized), but:
- while a list of a million elements is being built, there are about 30 copies;
- during a copy, the old and new arrays live side by side, so memory is temporarily 2.5x;
- a very large array becomes a humongous object in G1 and takes up separate regions.
If you know the size in advance:
List<RowDto> rows = new ArrayList<>(resultSet.expectedSize());
// or for an existing list
list.ensureCapacity(500_000);
There is a reverse problem too: if a list once grows to 1 million and then drops to 100 elements, the array does not shrink. For long-lived lists, trimToSize() or creating a new list gives the memory back.
In a heap dump (jmap/MAT), a large "retained size" of Object[] arrays and a big gap between size and elementData.length are signs of this problem.
Sign up to mark studied questions and save your progress.