Video in progress
In a JMH benchmark the stream pipeline came out as fast as a for loop, but in prod the same code is noticeably slower. What roles do "profile pollution" and a megamorphic call site play here?
Lambda calls inside a stream pass through a few shared places in JDK code (the ReferencePipeline sinks). In a benchmark only one lambda type is seen there, and the JIT inlines it. In prod hundreds of different lambdas pass through the same spot, the call site becomes megamorphic, and inlining and escape analysis stop. As a result virtual calls and boxing allocations come back.
📖 Answer
The basis of JIT optimization is the profile. C2 counts which classes arrived at each virtual call site:
- 1 type: monomorphic, inlined directly;
- 2 types: bimorphic, both variants inlined plus a check;
- 3 or more: megamorphic, an ordinary virtual call, no inlining.
In a stream, map(mapper) is in your code, but the mapper.apply(t) call is in a single method inside the JDK: ReferencePipeline$3$1.accept. Every map across the whole application passes through that one place. In an isolated JMH test only your lambda is there, so the result is excellent. In prod, after dozens of services' code has run, the profile is "polluted": megamorphic.
The consequence is more than one virtual call. Where inlining doesn't happen, escape analysis doesn't work either: Integer boxing, objects captured by lambdas, Optional, all turn into real heap allocations. That's why a conclusion like "allocation was zero in the benchmark" turns out wrong in prod.
How I check:
- A realistic profile in JMH: in the benchmark's
@Setup, warm up the same pipeline with several different lambdas, then measure. The difference is often several times. - In prod: async-profiler (CPU and
-e alloc), JFR. To see inlining decisions use-XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining(test environments only, the output is huge). - If the stream is long, inlining depth is a limit too. In Java 14
MaxInlineLevelwas raised from 9 to 15, so measurements from an old JDK don't carry over directly to a modern one.
When I change code: only if the profile clearly shows this method as hot. In that case, a plain for and primitive arrays for the hottest loop: there the call sites are in your own code and the profile is clean. In the other 99% of the code, streams stay.
This topic is the deepest answer to the interview question "are streams slow?": the problem isn't in streams themselves but in the JIT's profile at shared call sites. And it's also a lesson in how to write a benchmark.
Sign up to mark studied questions and save your progress.