Lesson 2 +10 XP

The V8 Engine Architecture

How V8 Executes JavaScript

The V8 engine, written in C++, compiles JavaScript directly into native machine code before executing it, rather than interpreting bytecodes line-by-line.

Key V8 Components

  1. Ignition (Interpreter): Generates and executes bytecode from AST (Abstract Syntax Tree).
  2. Turbofan (Optimizing Compiler): Optimizes hot functions (frequently run code) into high-performance machine code.
  3. Garbage Collector (Orinoco): Manages memory allocation in Heap memory using mark-and-sweep and generational garbage collection.

Memory Allocation in Node.js

  • Call Stack: Stores execution contexts, primitive values, and function call frames. Follows Last-In-First-Out (LIFO).
  • Memory Heap: Large unorganized memory region where objects, arrays, and functions are allocated.
function calculateTotal(price, tax) {
  return price + price * tax;
}

// Ignition interprets the code first; if called thousands of times,
// Turbofan compiles calculateTotal into native machine instructions.
for (let i = 0; i < 10000; i++) {
  calculateTotal(100, 0.05);
}

TL;DR

  • V8 uses a Just-In-Time (JIT) compilation model combining Ignition and Turbofan.
  • Functions called repeatedly are compiled to machine code for maximum speed.
  • Memory is split into the Call Stack (execution contexts) and Memory Heap (object storage).