V8 Optimization & Hidden Classes
V8 uses Just-In-Time (JIT) compilation and hidden classes (internal shape representations) to optimize property access. Code that is predictable in shape and types is compiled to fast machine code.
Hidden classes are like cookie cutters — V8 makes one cutter per object shape. If all your cookies have the same shape, V8 stamps them out lightning fast. Change the shape mid-batch (add/delete a property) and V8 has to throw away the cutter and carve by hand.
Hidden classes (V8's 'Maps') are created based on the order and names of properties added to an object. Objects with the same property assignment order share a hidden class, enabling V8 to use offset-based property access instead of hash table lookups. Adding properties out-of-order or conditionally creates different hidden classes and prevents optimization. Monomorphic call sites (always the same hidden class) are the fastest; polymorphic (2-4 shapes) are slower; megamorphic (5+) fall back to generic hash lookup.
V8's optimization pipeline: Ignition (interpreter, generates bytecode) → Maglev (mid-tier JIT, 2023) → TurboFan (optimizing JIT). TurboFan deoptimizes ('deopt') when assumptions are violated — e.g., an integer-typed variable suddenly receives a float. Deopt triggers a bailout to interpreted code and re-profiling. Arguments objects, try-catch blocks in hot functions, eval, and with can inhibit optimization. Monomorphic functions are inlined by TurboFan, eliminating call overhead. To profile V8 optimizations: node --prof script.js generates a V8 profiler log; node --trace-deopt shows deoptimizations.
V8 optimizes code by building hidden classes for object shapes and using inline caches at property access sites. For maximum performance: initialize all object properties in the constructor (same order every time), avoid deleting properties, keep function argument types consistent, and avoid mixing integers and floats in typed arrays. Predictable, monomorphic code is what TurboFan can compile to machine code.
delete obj.property is highly detrimental to V8 optimization — it changes the object's hidden class, breaking the inline cache. Instead of deleting, set the property to undefined (same type slot, different value) or null. For truly optional properties that shouldn't exist, use Map instead of plain objects.