Video in progress
What are monomorphic, bimorphic and megamorphic call sites, and how do they affect speed?
It depends on how many different classes show up at a call site at runtime: with one, the JIT inlines it directly; with two, it inlines both variants behind an if; with three or more, an ordinary virtual call usually remains and inlining is lost.
📖 Answer
What matters is not the code but the call site. One shape.area() line can be monomorphic in one place and megamorphic in another.
double total(List<Shape> shapes) {
double sum = 0;
for (Shape s : shapes) {
sum += s.area(); // this line: how many different classes arrive?
}
return sum;
}
- If only
Circlearrives, it is monomorphic. C2 inlinesCircle.area()and puts a cheap type check in front of it. CircleandSquaremake it bimorphic: both are inlined, with anifbetween them.Circle,Square,Triangleand others make it megamorphic. HotSpot usually calls through the vtable/itable here, with no inlining, and so no escape analysis either.
This is about nanoseconds. In an ordinary CRUD service you will never notice it. But in very hot loops (serialization, a parser, math) the difference can be several times.
Practical approaches, if the profile really points here:
- sort the array by type and process it in separate loops;
- sealed hierarchies and pattern matching
switchare sometimes friendlier to the JIT; - avoid passing different types through one shared "hot" method.
But measure first. It isn't worth breaking the architecture out of fear of megamorphic calls.
Sign up to mark studied questions and save your progress.