Overview Of V8 Garbage Collection In NodeJS

Overview of V8 Garbage Collection in Node.JS

V8 compiles JavaScript source code directly into machine code when it is first executed. There are no intermediate byte codes, no interpreter. Property access is handled by inline cache code that may be patched with other machine instructions as V8 executes.

V8 Heap organization

V8 heap organized into different spaces. Each space is composed of a set of pages. Pages are 1MB in size. For large-object-space, pages are larger in size. In addition to object, page also contains header and slot buffers, allocated in separate memory which forms list of object may refer to object stored in page.


It is small, independent of other spaces and is designed to be garbage collected very quickly. Most objects are allocated here.


Objects which may have pointers to other objects are stored in this space. Most objects are moved here after surviving in new-space for a while.


Objects which just contain raw data (no pointers to other objects) are stored in this space. Strings, boxed numbers, and arrays of unboxed doubles are moved here after surviving in new-space for a while.


This space contains objects which are larger than the size limits of other spaces. Each object gets its own mmap'd region of memory. Large objects are never moved by the garbage collector.


Code objects, which contain JITed instructions, are allocated here. This is the only space with executable memory (although Codes may be allocated in large-object-space, and those are executable, too).

Cell-space, property-cell-space, map-space

These spaces contain Cells, PropertyCells, and Maps, respectively. Each of these spaces contains objects which are all the same size and has some constraints on what kind of objects they point to, which simplifies collection.

How Optimally GC works

V8 reclaims memory used by objects those are no longer required during garbage collection process. In V8, object heap is segmented into two parts, new space where objects are created and old space to which objects surviving GC cycle are promoted. Once object is moved in GC cycle, V8 updates all the pointers to the object.

To ensure fast garbage collection V8,

  • Stops program execution when performing garbage collection
  • Processes only part of the heap in most cycles. This help in minimizing the impact of stopping the application.
  • Keep knowledge about exactly where all objects and pointers are in memory which helps to avoid falsely identifying objects as pointers may result in memory leaks. 

How to get V8 Version in running Node.JS

Process.versions.v8 attribute contains the version information of V8 version installed along with Node.js.


Forcing GC to run in Node.JS

Node.js allows running GC explicitly. GC can be accessed using below statement in node script file.

  1. global.gc();   

When run code add option ‘—expose-gc’, which exposes GC to global object.

  1. node --expose-gc test.js