V8 & memory

The V8 engine is Google’s open-source high-performance JavaScript and WebAssembly engine, written in C++. It is the core of both Google Chrome and Node.js. Understanding how V8 manages memory is crucial for preventing memory leaks and optimizing application performance.

1. The V8 Memory Structure (The Heap)


When a Node.js process starts, V8 allocates a chunk of memory called the Resident Set. The most important part of this is the Heap, which is divided into several areas:

A. New Space (Young Generation)

  • Purpose: Where most objects are initially allocated.

  • Characteristics: Small in size (typically 1–8 MB) but very fast to collect.

  • Mechanism: It uses a Scavenge algorithm. Most objects created here are short-lived (local variables, function arguments) and are cleared quickly.


B. Old Space (Old Generation)


  • Purpose: If an object survives two "Scavenge" cycles in the New Space, it is moved (promoted) here.

  • Characteristics: Much larger than the New Space. This is where long-lived data (like global variables or cached data) resides.

  • Mechanism: Uses the Mark-Sweep-Compact algorithm, which is more resource-intensive but happens less frequently.


C. Large Object Space


  • This area is for objects that exceed the size limits of other spaces. These are not moved by the garbage collector to avoid the high cost of copying large amounts of data.


2. Garbage Collection (GC)


Garbage collection is the process of reclaiming memory that is no longer being used by the application. V8 uses a "Generational" approach.

  1. Minor GC (Scavenger): Cleans the New Space. It’s incredibly fast and happens frequently. It moves "live" objects to a "To-Space" and wipes the rest.

  2. Major GC (Mark-Sweep-Compact): Cleans the Old Space.

    • Marking: V8 traverses the "object graph" starting from the roots (global objects) to see what is still reachable.

    • Sweeping: It clears the memory of unreachable objects.

    • Compacting: It moves objects together to remove "fragmentation" (empty gaps in memory), making room for new large objects.


3. Stack vs. Heap

It is important to distinguish between where different types of data are stored:


FeatureThe StackThe Heap
Data StoredPrimitive types (numbers, booleans) and pointers to objects.Complex objects (Objects, Arrays, Closures).
ManagementManaged by the OS (LIFO - Last In, First Out).Managed by the V8 Garbage Collector.
SpeedExtremely fast.Slower (requires GC cycles).



4. Memory Limits


By default, V8 limits the heap size to prevent a single Node.js process from consuming all system memory.

  • 64-bit systems: Typically ~1.5 GB.

  • 32-bit systems: Typically ~700 MB.

You can manually increase this limit using the --max-old-space-size flag if you are processing massive amounts of data:


node --max-old-space-size=4096 app.js # Increases limit to 4GB


5. Common Causes of Memory Leaks


Even with an advanced garbage collector, you can still run out of memory (OOM) if you prevent V8 from cleaning up:

  • Global Variables: Variables attached to the global object are never collected.

  • Closures: A function inside a function that keeps a reference to a large outer variable.

  • Forgotten Timers: A setInterval that keeps running and referencing objects long after they are needed.

  • Event Listeners: Adding listeners to an object (like process.on('uncaughtException')) without removing them when they are done.


6. How to Monitor Memory

You can check memory usage within your code using process.memoryUsage():


console.log(process.memoryUsage());
/* 
Returns:
{
  rss: 'Resident Set Size (Total memory used)',
  heapTotal: 'Total size of the heap',
  heapUsed: 'Actual memory used by your objects',
  external: 'Memory used by C++ objects linked to JS'
}
*/