Chapter 11: JavaScript Engines and V8
Chapter 11 of 15
Chapter 11: JavaScript Engines and V8
11.1 How JavaScript Engines Work
JavaScript engines convert JavaScript code into machine code that computers can execute. Understanding engines helps write performant code.
Major JavaScript Engines:
- V8: Chrome, Node.js, Edge
- SpiderMonkey: Firefox
- JavaScriptCore: Safari
- Chakra: Legacy Edge
V8 Engine Architecture:
// V8 compilation pipeline:
// 1. Parser - Converts source code to AST (Abstract Syntax Tree)
// 2. Ignition - Interpreter, generates bytecode
// 3. TurboFan - Optimizing compiler, generates optimized machine code
// 4. Orinoco - Garbage collector
Just-In-Time (JIT) Compilation:
- Code starts as interpreted (fast startup)
- Hot code (frequently executed) gets compiled to optimized machine code
- Optimizations based on runtime behavior
- Deoptimization if assumptions become invalid
11.2 Optimization Strategies
Hidden Classes:
// Good: Consistent property order
function Point(x, y) {
this.x = x;
this.y = y;
}
// Bad: Different property order creates different hidden classes
function BadPoint(x, y) {
if (x > 0) {
this.x = x;
this.y = y;
} else {
this.y = y;
this.x = x;
}
}
Inline Caching:
// V8 caches property lookups
// Accessing obj.property multiple times is optimized
const obj = { property: 'value' };
for (let i = 0; i < 1000; i++) {
console.log(obj.property); // Cached lookup
}
11.3 Garbage Collection
V8 uses generational garbage collection with two main spaces:
- Young Generation: New objects, fast collection
- Old Generation: Long-lived objects, slower collection
// Memory management tips:
// 1. Avoid memory leaks
// 2. Use object pools for frequently created objects
// 3. Clear large arrays/objects when done
// 4. Use WeakMap/WeakSet for temporary references