Video in progress

Strong Middle 🧺 Collections

How do ArrayList.removeAll() and retainAll() work, and why do they get slow when you pass a big List as the argument?

ArrayList.removeAll(c) calls c.contains(e) for each of its elements. If c is a List, each contains is O(m) and the total is O(n·m): with 100,000 × 100,000 that is billions of comparisons. If you turn the argument into a HashSet, the work drops to O(n).

📖 Answer

Inside ArrayList this is batchRemove: it walks the array once and moves the elements that stay forward. It is efficient itself; the problem is the argument.

List<Long> all = loadIds();        // 200,000
List<Long> processed = loadDone(); // 150,000

all.removeAll(processed);                  // 200k × 150k equals calls: minutes
all.removeAll(new HashSet<>(processed));   // milliseconds

On one service, code like this ran in a daily sync. It went unnoticed while the data was small, then over a year the volume grew tenfold and the job stretched to 40 minutes. If you see ArrayList.indexOf → Long.equals in a flame graph, that is a typical sign.

A few more subtle points:

  • HashSet.removeAll(c) (more precisely AbstractSet.removeAll) picks a strategy by size: if the Set is larger than the argument, it iterates over the argument and removes from the Set; otherwise it iterates over itself and calls c.contains for each element. In the second case, if c is a List, it is O(n·m) again. So the same code runs fast or very slowly depending on the data size.
  • retainAll always relies on c.contains, so the argument should preferably be a Set.
  • Comparison goes through equals, so with elements whose equals is written wrong, the result is wrong too.

The rule is the same if you write it with a stream: in filter(id -> !done.contains(id)), done really must be a Set. In code review, when I see removeAll( or contains( inside a loop, the first thing I check is the argument type.