Overview
Garbage collection in Node.js is primarily managed by the V8 JavaScript engine, which uses several algorithms to automatically reclaim memory that is no longer in use by the application. This process helps avoid memory leaks and keeps your application running smoothly.
Key Concepts
- Managed Heap: All objects and data are stored in the V8 heap, which is divided into different spaces based on the age and size of objects.
- Roots & References: Garbage collection starts from a set of root objects (like global variables) and traverses all references. Objects not accessible from these roots are considered garbage.
The Mark-and-Sweep Algorithm
- Mark Phase: Starting from roots, mark all reachable (still in use) objects.
- Sweep Phase: Unmarked objects are not referenced and will be cleaned up (memory reclaimed).
Generational Garbage Collection
- New Space (Young Generation): Newly created objects are stored here. Most objects die young and are collected quickly.
- Old Space (Old Generation): Objects that survive several GC cycles are promoted here. Cleanup happens less frequently but is more costly.
Minor GC (Scavenge)
- Quick collection in the New Space.
- Example: Short-lived variables inside a function.
Major GC
- Cleans Old Space; more comprehensive and pauses execution longer.
- Example: Large objects held globally that are eventually dereferenced.
Useful Node.js Garbage Collection Flags
-
--expose-gc: Manually trigger GC withglobal.gc()for debugging. -
--max-old-space-size=4096: Increase heap size (in MB) for memory-intensive apps.
Example:
// When using --expose-gc flag
if (global.gc) {
global.gc(); // Force garbage collection
} else {
console.log('Garbage collection is not exposed');
}
Summary
- The V8 engine automates memory management using advanced algorithms.
- Most memory is reclaimed from short-lived objects; long-lived objects require occasional major GC.
- Developers can control and monitor GC for tuning performance when necessary.
Top comments (0)