Video in progress

When do persistent (structural sharing) collections (Vavr, PCollections) beat the JDK's List.copyOf approach?

When you need a new version on every change and the collection is large: a persistent structure reuses most of the old version, so a "copy" is O(log n), not O(n). For small collections and rare changes, the JDK's plain copy is simpler and faster.

📖 Answer

The JDK's immutable collections are designed for "built once, then only read". To add one element, you have to copy the entire list:

List<Event> next = Stream.concat(current.stream(), Stream.of(e)).toList(); // O(n)

Persistent structures (usually based on a HAMT or a tree) create a new version but share the unchanged parts with the old one:

io.vavr.collection.List<Event> v1 = io.vavr.collection.List.of(a, b);
io.vavr.collection.List<Event> v2 = v1.prepend(c);  // v1 didn't change, no copy

When it pays off:

  • the state is shared among many threads and updated often: every update publishes a new version with AtomicReference.compareAndSet, and readers take no lock;
  • you need "undo", history or versions (configuration, document edits, aggregate state in event sourcing);
  • a large domain model in a functional style.

When it doesn't:

  • most collections have 10–100 elements: a copy takes a few microseconds, and the extra pointers from structural sharing slow down iteration;
  • the data is built once and then only read;
  • the team doesn't know these libraries, and integrating them with JPA, Jackson and Spring requires extra adaptation.

From an architecture point of view, I keep persistent collections inside a module and convert to a JDK type at the boundary (toJavaList()). That way one component's choice doesn't spread through the whole system.

A simple test before deciding: an allocation profile under real load. If copying doesn't show up in the profile, there is no problem, and no need for the library either.