liveBook · Manning

Polymorphism

As explained in JavaScript in Depth

A classification of a function or operation whose observed inputs have a small, bounded set of relevant types or shapes.

A call site is polymorphic when it has observed between two and four object shapes. V8 records those shapes in an inline cache so property access can reuse known locations instead of repeating full lookups. section 5.10.2

Watching a property load widen

For `readX(point)`, the first object shape makes the property-load site monomorphic. A second shape changes it to polymorphic; the third and fourth remain polymorphic while adding maps. A fifth shape makes it megamorphic. The transition is visible in `--log-ic` output as `0 → 1 → P → P → P → N`. section 5.10.2

function readX(point) {
  return point.x;
}

Use the minimal property-reading function to locate the call site whose observed shapes determine the inline-cache state. section 5.10.2

const shapes = [
  { x: 1, a: 0 }, { x: 2, b: 0 }, { x: 3, c: 0 },
  { x: 4, d: 0 }, { x: 5, e: 0 }, { x: 6, f: 0 },
];
 
let total = 0;
for (let limit = 1; limit <= shapes.length; limit++) {
  for (let i = 0; i < limit * 2; i++) total += readX(shapes[i % limit]);
}

Run the shape sequence to reproduce the progression from monomorphic through polymorphic to megamorphic behavior. section 5.10.2

Use these distinctions when interpreting V8 performance behavior:

  • Monomorphic means one observed shape; polymorphic means two to four; megamorphic means more than four. section 5.10.2
  • Polymorphic degradation is gradual: 20 million loads take 31.73 ms with two shapes and 41.88 ms with four, versus 22.31 ms with one. section 5.10.2
  • Five or more shapes can trigger megamorphic behavior, with the benchmark reaching 108.29 ms for five shapes. section 5.10.2

How JavaScript in Depth covers it

How deep it goes
Defines shape thresholds, traces inline-cache transitions, and measures slowdown without detailing optimized machine-code internals.
Examples
Uses a readX function, six differently shaped objects, --log-ic output, and Node.js 24 property-load measurements.
What it assumes
Assumes JavaScript objects, property access, function call sites, and basic familiarity with V8 terminology.
What you can do after
Diagnose property-access slowdowns by correlating observed object shapes with inline-cache states and benchmark results.
How it connects
Connects object shapes, hidden classes, inline caches, type feedback, megamorphism, and deoptimization.

Also explained in

Compare how 12 books explain polymorphism →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.