Video in progress

How do interfaces and polymorphism affect performance when there are many layers of abstraction? What does the JIT do here?

In most cases they have almost no effect: if the JIT sees one or two implementations at a call site, it inlines the call. The problem is a megamorphic call site: when three or more types are mixed, virtual dispatch and the lack of inlining become noticeable in a hot loop.

📖 Answer

HotSpot collects a type profile for every call site:

  • monomorphic: only one class was seen. The JIT inlines directly, guarded by a type check. The cost is close to zero.
  • bimorphic: two classes. Inlined with two branches, still fast.
  • megamorphic: three or more. Dispatch goes through the vtable/itable, with no inlining. Because nothing is inlined, escape analysis and loop optimizations don't work either, and that is the real loss.

So the claim "interfaces are slow" is wrong. In a typical Spring service, the OrderRepository interface has one implementation, so the call site is monomorphic.

When it does matter:

// hot loop, 10 million elements, 5 different Shape implementations mixed
double total = 0;
for (Shape s : shapes) total += s.area(); // megamorphic

How to find such a spot:

  • profile first: async-profiler or JFR. I don't optimize by guessing;
  • -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining: the output shows which call sites were not inlined and why (for example "virtual call");
  • a JMH microbenchmark to compare the mono and mega cases.

Solutions, if the profile points at this spot:

  • process the data grouped by type (inside each group the call site is monomorphic);
  • a sealed hierarchy and a switch with pattern matching: the compiler produces a chain of type checks, which the JIT optimizes well;
  • thin out the abstraction on the hot path.

But in a real backend, 95% of the time goes to I/O, SQL and serialization. Before bending your design for the cost of abstraction, a profile has to prove it.