Garbage Collection Mechanism in JavaScript

Garbage Collection Mechanism in JavaScript

In JavaScript, garbage collection is an automatic memory management process responsible for identifying and releasing memory space that is no longer in use, thereby preventing memory leaks.

1. Basic Concepts of Garbage Collection
The JavaScript engine automatically allocates memory when creating variables, objects, functions, etc. When this memory is no longer needed, the garbage collector automatically releases it. The main goal is to identify objects that are "no longer needed."

2. How to Determine When Memory Is No Longer Needed?
Core algorithms: Reference counting and mark-and-sweep.

Reference counting (early method):

  • Principle: Tracks the number of times each value is referenced.
  • When a variable is declared and assigned a reference value, the reference count is 1.
  • When the value is assigned to another variable, the reference count increases by 1.
  • When the variable holding the reference to the value is overwritten by another value, the reference count decreases by 1.
  • When the reference count reaches 0, it indicates the value is no longer accessible and can be reclaimed.

Mark-and-sweep (modern mainstream):

  • Principle: Starts from root objects (global objects) and marks all reachable objects.
  • Steps:
    1. The garbage collector starts from root objects, traverses all referenced objects, and marks them as "reachable."
    2. It then traverses the entire heap memory and treats unmarked objects as "unreachable."
    3. Finally, it clears these unreachable objects and releases their memory.

3. Optimization Strategies in Modern Garbage Collection

  • Generational collection: Divides memory into the new generation and the old generation.
  • New generation: Stores short-lived objects, with frequent garbage collection.
  • Old generation: Stores long-lived objects, with less frequent garbage collection.
  • Incremental marking: Splits the marking process into small steps to avoid long blocking of the main thread.

4. Common Scenarios for Memory Leaks

  • Accidental global variables.
  • Uncleared timers and callback functions.
  • Unreleased DOM references.
  • Improper use of closures.

Understanding the garbage collection mechanism helps in writing more efficient JavaScript code and avoiding memory leak issues.