Course contentsShow
← JavaScript
Lesson 1910 of 2,72340. PerformanceFree lesson

Monomorphic vs Polymorphic Sites

Code that sees one shape (monomorphic) is faster than code seeing many shapes (polymorphic).

Monomorphic vs Polymorphic Sites

What you'll learn: Why JavaScript engines run faster when functions consistently see objects with the same shape.

The Core Idea

A call site (a location in your code where a function or operation executes) is monomorphic if it always encounters objects with the same hidden class. It's polymorphic if it sees objects with different hidden classes. The engine optimizes heavily for monomorphic sites because it can make assumptions and skip checks.

Think of it like a factory assembly line: if every item coming down the line is identical, workers can perform their task without stopping to check what they're handling. But if different items arrive, they must inspect each one first—slowing everything down.

Why Shape Matters

When V8's optimizing compiler encounters a function that always receives objects of the same shape, it generates highly specialized machine code. It "knows" exactly where each property lives in memory.

If that same function suddenly receives objects with different shapes, V8 must either:

  • Deoptimize back to slower code
  • Generate more generic (slower) code that handles multiple cases

The Performance Gap

Monomorphic sites can be 100x faster than polymorphic ones in tight loops or hot code paths. The engine can inline property accesses directly without dictionary lookups or additional checks.

Polymorphic sites (typically 2-4 different shapes) are slower but still optimizable. Megamorphic sites (5+ shapes) often fall back to slow dictionary-style lookups.

Practical Implication

Create objects consistently. If you have a function that processes user objects, ensure all user objects share the same hidden class by initializing properties in the same order with the same types.

Key Takeaway: Keep your call sites monomorphic—feed functions objects with identical shapes to unlock maximum performance from the JavaScript engine's optimizing compiler.