Engines & JIT Compilation

How an Engine Runs Your Code

Browsers and Node.js contain a JavaScript engine: V8 (Chrome, Edge, Node), SpiderMonkey (Firefox), JavaScriptCore (Safari).

  1. Parse the source into an Abstract Syntax Tree (AST).
  2. Interpret: compile the AST to bytecode and start running it immediately (V8: Ignition).
  3. Profile: watch which functions are "hot" (run often) and what types they see.
  4. Optimise: compile hot functions to fast machine code based on those types (V8: TurboFan).
  5. Deoptimise: if the assumptions break (e.g. a number becomes a string), fall back to bytecode.

Write Engine-friendly Code

  • Keep the types of variables and function arguments consistent.
  • Create objects with the same properties in the same order (they then share a "hidden class" / shape).
  • Avoid adding or deleting properties on hot objects after creation.
  • Prefer arrays of a single type (all numbers, or all objects of the same shape).