V8 compiles JavaScript to machine code using a two-tier system: Ignition (interpreter, fast startup) and TurboFan (optimizing compiler, fast execution). Between them lies the secret to JavaScript's near-native performance: hidden classes and inline caching. This article explains how V8 makes your code fast and what patterns accidentally slow it down.
Prerequisites: None — but familiarity with JavaScript functions and objects helps.
1. The Two-Compiler Pipeline
V8 uses a layered approach:
Source Code → Parser → AST → Ignition (interpreter) → Bytecode
↓ (hot functions)
TurboFan (compiler) → Optimized Machine Code
↓ (bailout/deopt)
Back to Ignition (bytecode)
Loading editor...
2. Hidden Classes (Shape) — How V8 Optimizes Objects
V8 doesn't use dictionary lookups for object properties. It assigns each object a hidden class (also called a "Shape" or "Map") that describes its property layout:
Loading editor...
The hidden class is determined by property order:
Loading editor...
3. Inline Caching (IC) — Remembering Property Locations
V8 caches the location of properties the first time it looks them up. This is called inline caching:
Loading editor...
4. Polymorphic and Megamorphic — When Caching Fails
Loading editor...
5. The Optimization / Deoptimization Cycle
TurboFan makes assumptions based on observed types. If those assumptions break, it deopts — throws away the optimized code and falls back to the interpreter:
Loading editor...
6. What Stays Fast in V8
Loading editor...
Key Takeaways
- V8 uses Ignition (interpreter) for quick startup and TurboFan (compiler) for hot functions.
- Hidden classes map property names to offsets — like C structs, not hash maps.
- Inline caching remembers which hidden class + offset a property was at — the key to fast property access.
- Monomorphic (1 shape) → fast. Polymorphic (2-4 shapes) → OK. Megamorphic (5+) → slow.
- Deoptimization happens when optimized code's assumptions are violated — e.g., type changes, new properties added.
- Always initialize properties in the same order, and prefer constructors to create consistent object shapes.
Next: V8 #2 — Memory Leaks & Garbage Collection — the four SPA leak patterns and how mark-and-sweep works.
