Node.js is built on Google’s V8 engine, and V8’s garbage collection mechanism is one of its core performance features. In this article, we’ll explore the three primary garbage collection algorithms used in V8: Mark-Sweep, Mark-Compact, and Scavenge, along with their working principles and application scenarios.
V8’s Memory Partition Model
Before diving into garbage collection algorithms, we need to understand V8’s memory partition model. V8 divides memory into two main regions:
Young Generation
- Contains objects with short lifespans.
- Typically small in size (e.g., a few MB).
- Uses the Scavenge algorithm for garbage collection.
Old Generation
- Contains objects with longer lifespans.
- Typically larger in size (e.g., hundreds of MB).
- Uses the Mark-Sweep and Mark-Compact algorithms for garbage collection.