Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

A hot loop calls shape.area() on a List<Shape>. With only Circle and Square in the list it is fast. After adding Triangle objects to the same list, the loop becomes noticeably slower. Explain why.

The JIT records which receiver types reach each call site. While only Circle and Square appear, the call shape.area() is bimorphic, so C2 inlines both area() bodies behind a quick type check. Once Triangle joins the same list, the site sees three types and becomes megamorphic, so C2 emits a real virtual call through the vtable or itable and cannot inline, losing the optimisations that depended on seeing the method body. Splitting the work per type can help, but we measure with JMH first, and in most business code the effect is small next to I/O.

Why this question is asked

This is a nice example of the JVM's performance depending on what the program has seen, not only on what it says. The code did not change, only the data, and yet the loop got slower. Interviewers ask it to check that we understand profiling, inlining and virtual dispatch, and that we know when it actually matters. In this answer, we will recap virtual calls, set up the example, see what C2 does with one, two and three types, measure it properly with JMH, and look at the mitigations and when they are worth it.

1A Quick Recap of Virtual Calls

When we call shape.area() and Shape is an interface or a class with overriding subclasses, the method that runs depends on the object's actual class at runtime. That is a virtual call. The classic way to perform one is through a table: each class has a vtable, a list of addresses of its methods (or an itable for interface methods), and the call loads the object's class, looks up the slot for area() and jumps to it. That costs a few memory loads and an indirect jump, but the bigger cost is that the compiler cannot see which code will run, so it cannot inline it.

2Reproducing the Slowdown

Here is the loop. We fill the list first with two types, then with three, and run the same method.

Java
sealed interface Shape permits Circle, Square, Triangle { double area(); }
record Circle(double r) implements Shape { public double area() { return Math.PI * r * r; } }
record Square(double s) implements Shape { public double area() { return s * s; } }
record Triangle(double b, double h) implements Shape { public double area() { return 0.5 * b * h; } }
static double total(List<Shape> shapes) {
double sum = 0;
for (Shape s : shapes) sum += s.area(); // the call site the JIT profiles
return sum;
}
// shapes = 1,000,000 Circles and Squares, mixed: ~1.1 ms per call (example)
// shapes = 1,000,000 Circles, Squares and Triangles, mixed: ~2.9 ms per call (example)

Notice that sealed does not help here: the JIT still decides from the profile at the call site, and a sealed interface with three permitted classes is still three receiver types. The numbers are illustrative; the size of the effect depends on the CPU and on how much work area() does.

3What C2 Does With One, Two and Three Types

While the method runs at C1 level 3, the JIT records a type profile at the call site: which classes the receiver had and how often. C2 reads that profile when it compiles total().

With one type seen, the site is monomorphic. C2 inlines that class's area() directly, guarded by a cheap check of the object's class; if another class ever shows up, the guard fails and the code deoptimises. With two types, the site is bimorphic, and C2 inlines both bodies behind an if-else on the class. In both cases, area() is now ordinary code inside the loop, and C2 can optimise across it.

With three or more types, the site is megamorphic. HotSpot's C2 inlines at most two receiver types from the profile. So it emits a real virtual call through the vtable or itable instead. There is one exception: if one type strongly dominates the profile, around 90 percent by default, C2 may still inline that one behind a guard and use a virtual call for the rest. In our mixed list no type dominates, so every iteration makes a full call.

Call site shape and what C2 emits
Types seenShapeCode C2 generates
1monomorphicclass check, then inlined body
2bimorphicif-else on class, both bodies inlined
3 or moremegamorphicvtable or itable call, no inlining
3+, one about 90%megamorphic, dominantdominant type inlined, call for the rest

4Why Losing Inlining Costs So Much

The call instruction itself is cheap. What we lose is everything inlining enables. With area() inlined, C2 can keep sum in a register across iterations, hoist the load of Math.PI out of the loop, avoid saving and restoring registers around a call, and sometimes unroll the loop or use vector instructions. Behind a virtual call, each iteration must spill state, jump indirectly, run a separately compiled method and return, and the CPU's branch predictor has to guess the target among three. For a tiny method like area(), that overhead can be bigger than the useful work, which is why the loop slows down by a factor rather than by a few percent.

5Measuring It Properly With JMH

Before changing code, we measure with JMH, the Java Microbenchmark Harness, which handles warmup, forks fresh JVMs so profiles from one test do not leak into another, and consumes results so the JIT cannot delete the work.

Java
@State(Scope.Benchmark)
public class ShapeBench {
@Param({"2", "3"}) int types;
List<Shape> shapes;
@Setup public void setup() { shapes = Shapes.mixed(1_000_000, types); }
@Benchmark public double total() { return Shapes.total(shapes); }
}
// Benchmark (types) Mode Cnt Score Units (example results)
// ShapeBench.total 2 avgt 10 1.12 ms/op
// ShapeBench.total 3 avgt 10 2.87 ms/op

Forking matters especially here, because the type profile is the whole story. If both cases ran in one JVM, the second would inherit a polluted profile from the first and the comparison would be meaningless.

6Mitigations and When They Matter

If the measurement shows the call matters, we can keep each call site monomorphic or bimorphic. One way is to process each type in its own loop, for example by keeping separate lists of circles, squares and triangles, so each loop's call site sees one type. Another is to replace the virtual call with a switch over the sealed type, which Java 21 pattern matching makes clean; the switch compiles to type checks with each case's code inlined. A third is to store the data in a layout that does not need dispatch at all, such as arrays of dimensions per shape type.

But we should keep this in proportion. In most business code, a request spends milliseconds in database calls and network I/O, and a megamorphic call costs nanoseconds. Rewriting code for monomorphism is only worth it in tight numeric or data-processing loops that the profiler shows are hot.

Java
static double total(List<Shape> shapes) {
double sum = 0;
for (Shape s : shapes) {
sum += switch (s) { // type checks, no virtual call
case Circle c -> Math.PI * c.r() * c.r();
case Square q -> q.s() * q.s();
case Triangle t -> 0.5 * t.b() * t.h();
};
}
return sum;
}
// 3 types, mixed: ~1.3 ms per call (example)

7Follow-up questions

Does making the classes final help?

Not for this case. final helps when the static type is a class with no overrides, because the JIT then knows the exact target. Here the static type is the interface Shape with three implementations, so the JIT still needs the type profile and still sees three receivers.

Can the order of objects in the list matter?

The profile counts types, so order does not change whether the site is megamorphic. But it matters for the CPU's branch predictor: a list sorted by type, all circles then all squares then all triangles, makes the indirect jump much easier to predict, so the megamorphic loop runs faster than with a random mix.

Is the limit of two types fixed?

In C2 the bimorphic limit is built into its inlining policy and is not a tunable we should change. Other compilers differ; Graal, for example, can inline more receiver types at a polymorphic site. That is one reason the same code can perform differently on GraalVM.

8Conclusion

In this answer, we saw that the JIT profiles receiver types at each call site and that C2 inlines one or two of them behind type checks. When Triangle joined the list, shape.area() became megamorphic, C2 switched to a vtable or itable call, and the loop lost inlining and everything that depends on it, which matters a lot for a tiny method in a hot loop. We measured with JMH in forked JVMs, kept call sites monomorphic with per-type loops or a switch over the sealed type, and remembered that in most business code I/O dominates.

What to say in the interviewAbout 90 seconds aloud

Open with

The JIT profiles every call site while the method runs at the C1 profiling tier, recording which receiver classes it sees. With only Circle and Square, shape.area() is bimorphic, so C2 inlines both area methods behind a quick class check.

Then, if they want more

Once the body is inlined, C2 can optimise the whole loop: keep the sum in a register, hoist constants, avoid call overhead, maybe unroll. When Triangle objects arrive, the site sees three types, which makes it megamorphic.

C2 only inlines up to two receiver types, unless one type dominates at around 90 percent, so now it emits a real virtual call through the itable for every element.

The call itself is a few nanoseconds, but losing inlining loses all the optimisations that depended on seeing the method body, and for a tiny method like area that overhead is bigger than the work. To fix it I would first measure with JMH, forking per case so profiles do not leak.

If it matters, I would keep call sites monomorphic, for example with a separate loop per type or a pattern-matching switch over the sealed interface. But I would also say that in normal business code a megamorphic call is noise compared with database and network time, so this is only worth it in hot numeric loops.

About this answer

Last updated
12 November 2026
Versions it names
Java 21
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A hot loop calls shape.area() on a List<Shape>. With only Circle and Square in the list...": https://scrivio-interview-library.netlify.app/java/jit-compilation/82e0c4b9f2/