Video in progress

When does a parallel stream really speed things up, and when does it run slower than the sequential version? How do you decide?

Parallelism pays off only when the workload is large (number of elements × cost per element), the source splits well, the operations are independent and CPU-bound. With a small list, a LinkedList, I/O or a requirement to preserve order, it is often slower. The decision is made only by measurement.

📖 Answer

A parallel stream isn't free: splitting, submitting tasks to the ForkJoinPool and merging results all add cost. Doug Lea's rough rule: if N (elements) × Q (work per element) is below about 10,000, don't expect any gain from parallelism.

Cases that speed up:

  • an array, ArrayList, IntStream.range: they split evenly;
  • heavy computation per element (cryptography, images, complex parsing);
  • terminal operations that are cheap to merge, like sum, max, count.

Cases that slow down:

  • LinkedList, Stream.iterate, Files.lines: they split badly;
  • sorted, distinct, limit, findFirst on an ordered stream: buffering and synchronization to preserve order;
  • collect(groupingBy(...)): a separate Map per chunk, and merging them is expensive;
  • lots of boxing: memory bandwidth becomes the limit, not the cores;
  • if the container is given 2 CPUs, there's almost no parallelism.

How I decide:

  1. I write the sequential version first.
  2. I check in the profiler that this code really is a hot path.
  3. I measure both variants with JMH on realistic data volume, in an environment close to the core count in prod.
  4. If the speedup is less than 2x, I usually keep the sequential one: the risks that come with parallel code (the shared pool, determinism) aren't worth it.

A web-service angle too: requests already run in parallel. Taking all the cores inside a single request raises the latency of other requests. Throughput barely grows, and p99 gets worse.