Sub topic 9
Monomorphic, Polymorphic, and Megamorphic Call Sites
This chapter assumes you already know what a hidden class (a V8 map) is, how adding properties creates shape transitions, and how an inline cache stores a map-to-offset pair at a property access site. The question here is narrower: what happens to that cache when a single site sees more than one shape, and how much does it cost?
The States of an Inline Cache
Each property access in a function, such as o.x, has its own slot in the function's feedback vector. That slot holds the inline cache (IC) state for that site and nothing else. The state describes how many distinct maps have passed through the site so far.
| State | Maps seen | What the cache stores | Typical cost |
|---|---|---|---|
| Uninitialized | 0 | Nothing yet | Full runtime lookup on first run |
| Monomorphic | 1 | One map and one offset | One map compare, then a direct load |
| Polymorphic | 2 to 4 | A short list of map and handler pairs | A few compares, then a direct load |
| Megamorphic | More than 4 | Nothing local; falls back to a shared global cache | Hash lookup, no specialization |
The limit of four comes from V8's current kMaxPolymorphism setting. Other engines pick different thresholds, and V8 could change this one, so don't treat the number as part of the language.
The transitions only go one way. Once a site is megamorphic, it normally stays megamorphic for the life of that feedback vector, even if every later object has the same shape. A brief burst of unusual objects early in a program can leave a hot site generic for good.
What Each State Means for Optimized Code
The IC state matters twice. The interpreter and baseline tiers use it on every execution, and the optimizing compilers (Maglev and TurboFan) read it as type feedback when they compile the function.
- Monomorphic. The optimizer emits one map check followed by a load from a fixed offset. If the check fails, the code deoptimizes. Because the shape is known, later operations on the loaded value can be specialized too, and calls can be inlined.
- Polymorphic. The optimizer emits a chain of map checks, one branch per known map, each with its own fixed-offset load. If every map stores
xat the same offset, V8 can merge the branches. This is still fast, but each extra map adds a compare and makes the code larger. - Megamorphic. The optimizer has no useful shape information. It emits a call to a generic load stub, which hashes the (map, property name) pair into a global megamorphic stub cache. A hit there is reasonably quick. A miss means a full lookup in the runtime. In both cases the compiler can't make assumptions about the result, so optimizations further along that rely on knowing the type are lost.
Measuring the Difference
The script below runs two functions that do the same thing. Each function is its own source-level function, so each has its own feedback vector. One sees a single shape. The other sees twenty shapes, each made by adding a different property before x.
// Run with: node ic-states.js
const { performance } = require('node:perf_hooks');
function makeShape(i) {
const o = {};
o['p' + i] = i; // a different first property gives a different map
o.x = i;
return o;
}
const SHAPES = 20;
const N = 2_000_000;
const mono = [];
const mega = [];
for (let i = 0; i < N; i++) {
mono.push(makeShape(0)); // always the same map
mega.push(makeShape(i % SHAPES)); // 20 different maps
}
function sumMono(arr) {
let s = 0;
for (let i = 0; i < arr.length; i++) s += arr[i].x;
return s;
}
function sumMega(arr) {
let s = 0;
for (let i = 0; i < arr.length; i++) s += arr[i].x;
return s;
}
function time(label, fn, arr) {
fn(arr); // warm up so the optimizing tiers kick in
fn(arr);
const t0 = performance.now();
let r = 0;
for (let k = 0; k < 10; k++) r += fn(arr);
const t1 = performance.now();
console.log(`${label}: ${(t1 - t0).toFixed(1)} ms (checksum ${r})`);
}
time('monomorphic', sumMono, mono);
time('megamorphic', sumMega, mega);On a typical machine the megamorphic version runs several times slower, but the exact ratio depends on the Node version, the CPU, and memory layout. Treat the output as a demonstration of the direction of the effect. Don't treat it as a constant you can quote. To see a polymorphic case, change SHAPES to 3 and run it again. The gap should get much smaller.
To check states directly, recent Node versions accept node --log-ic ic-states.js (older versions used --trace-ic). This writes a v8.log file. You can load that file into the V8 System Analyzer web tool, which lists each IC site with its transitions, such as 0->1 (uninitialized to monomorphic), 1->P, and P->N (polymorphic to megamorphic).
Gotchas That Create Extra Shapes
Most accidental polymorphism comes from code that creates more maps than you expected. Code that deliberately mixes types is a less common cause.
Class hierarchies
Instances of a subclass have a different map from instances of the base class, even when they hold the same fields. A base-class method that reads this.x is shared by every subclass, so its access site sees one map per subclass.
class Shape { constructor(x) { this.x = x; } getX() { return this.x; } }
class Circle extends Shape {}
class Square extends Shape {}
class Triangle extends Shape {}
const items = [new Shape(1), new Circle(2), new Square(3), new Triangle(4)];
let total = 0;
for (const s of items) total += s.getX(); // this.x site: 4 maps, polymorphic
console.log(total);Add a fifth subclass and that site becomes megamorphic. This is normal in object-oriented code and usually fine. It matters only when profiling shows the method is hot.
Field representation changes
V8 tracks a representation for each field, such as small integer (Smi), double, or heap object. If x starts out as 1 in some objects and 1.5 in others, V8 generalizes the field and deprecates the old map. Objects still on the deprecated map migrate lazily, so for a while a site can see both the old and new maps.
Optional properties and different initialization paths
Objects with "the same fields" built by different code paths, such as an object literal in one place and a constructor plus a later assignment in another, often end up with different maps. Factory functions that sometimes add a property conditionally split one logical type into two shapes.
Generic helpers
A utility like function get(obj, key) { return obj[key]; } that is called with many object types and many keys becomes megamorphic almost immediately. This is expected. The real problem starts when such a helper sits in a hot loop that would otherwise be monomorphic.
Decision Criteria
Polymorphism is not a bug. Use these questions to decide whether a site deserves attention:
- Is the function hot in a profile? A megamorphic site in code that runs a hundred times costs nothing you can measure.
- Is the site megamorphic, or only polymorphic with two or three maps? Low polymorphism is usually cheap.
- Can you make the shapes uniform without hurting the design? Options include initializing every field in the constructor, always assigning properties in the same order, and keeping a field's value type consistent.
- If the variety is real, can you split the work by type, so that each loop or function handles only one shape?
Exercise
A function area(s) reads s.width and is called with objects from five factory functions that each produce a distinct map. After a refactor, all five factories return objects with the same map, but area stays slow in a long-running server process. Why, and what would bring the speed back?
Show answer
The s.width site went megamorphic before the refactor took effect, or early in the process while old-shaped objects were still in circulation. IC states don't move back toward monomorphic, so that site stays generic. Restarting the process with the uniform shapes in place from the start lets the site stay monomorphic. Making sure no code path still creates the old shapes keeps it monomorphic.
Exercise
In the benchmark, setting SHAPES to 4 and then to 5 gives noticeably different timings, even though only one shape was added. Explain the jump.
Show answer
V8's polymorphic limit is four maps. With four shapes the site stays polymorphic, and optimized code uses a short chain of map checks with direct loads. The fifth map pushes the site to megamorphic, so the optimizer switches to a generic stub-cache lookup and loses its type assumptions about the loaded value.