ReviseAlgo Logo

Performance & Optimization

Memory Management & Garbage Collection

Master memory management and garbage collection in JavaScript. Learn the Stack vs Heap allocations, reference counting limits, and V8 generational collection sweeps.

Last Updated: July 15, 2026 10 min read

1. Introduction

JavaScript automatically manages memory allocation using a Garbage Collector (GC). The engine allocates memory when variables or objects are created, and releases it when they are no longer reachable from the application's root scope.

2. Why It Matters

While garbage collection is automatic, it is not free. When the GC sweeps memory, it can temporarily pause code execution (known as Stop-The-World pauses). Understanding how the GC manages memory helps you avoid creating temporary objects in tight loops, preventing frame drops.

3. Real-World Analogy

Think of a Rent-A-Unit Storage Facility:

  • Allocating (Renting a locker): When you declare a variable or instantiate an object, the manager reserves a locker for you.
  • The Inspector (Garbage Collector): A facility inspector sweeps the lockers periodically.
    Reference Counting (Locker Keys): The inspector checks if anyone has a key to the locker. If no one holds a key (reference count is 0), the locker is emptied. However, if two lockers contain keys to each other but both owners lost their main building access keys, they remain locked forever (circular dependency memory leak).
    Mark-and-Sweep (Pathways from Lobby): The inspector starts at the lobby (the Root window/global scope) and follows the pathways. If they can walk to a locker, it is marked as active. If a locker is unreachable from the lobby, it is swept and emptied, resolving the circular dependency problem.

4. Stack vs Heap Allocations

V8 divides memory allocations into two areas:
The Stack: Stores static data (such as primitive values and function execution contexts) whose size is known at compile time. Allocation and deallocation are fast and managed automatically by the call stack.
The Heap: Stores dynamic data (such as objects, arrays, and functions) whose size can change at runtime. Accessing heap memory is slower and requires garbage collection sweeps to free.

5. Generational Garbage Collection

The V8 engine divides the heap into two generations:
New Space (Young Generation): Stores short-lived objects (typically 1-8 MB). Allocations here are cheap. V8 cleans this space frequently using a fast Scavenger algorithm.
Old Space (Old Generation): Stores objects that survived multiple scavenger sweeps. V8 cleans this space less frequently using a Mark-Sweep-Compact algorithm, which is slower but manages larger memory blocks.

6. Practical Example

This script demonstrates creating objects that become unreachable, making them eligible for garbage collection:

7. Common Mistakes

  • Relying on legacy Reference Counting assumptions: Early browsers used reference counting to manage memory, which failed to collect circular references. Modern engines use the Mark-and-Sweep algorithm, but circular references can still lead to leaks if they remain attached to global or parent scopes.

8. Quick Quiz

Q1: Which garbage collection algorithm is used by modern JavaScript engines to resolve circular reference memory leaks?

A) Reference Counting

B) Mark-and-Sweep

Answer: B — The Mark-and-Sweep algorithm traverses pointers starting from the root scope, sweeping any objects that are unreachable even if they reference each other.

9. Scenario-Based Challenge

The High-Frequency Object Pool Allocation:

A game loop instantiates bullet positions: new Bullet(x, y) 60 times per second, triggering frequent garbage collection sweeps and causing frame stutter. Redesign the state management using an object pool to recycle instances and prevent memory allocations.

10. Debugging Exercise

Explain why these node references cannot be garbage collected, and how to release them:

let cache = {
  // references a heavy DOM node
  element: document.getElementById('heavy-element') 
};

// Objective: remove the element from the DOM page document.getElementById('heavy-element').remove();

// Bug: the element is removed from the DOM, but it is not garbage collected! Why?

View Solution

Diagnosis: Although the element is removed from the DOM tree, the global cache object still holds a reference to it. Because it is still reachable from the root scope, the garbage collector cannot free it (creating a Detached DOM Node leak).

Fix: Set the reference to null or delete the cache key to release the memory:

document.getElementById('heavy-element').remove();
cache.element = null; // Release reference, allowing GC!

11. Interview Questions

🟢 Q1: Explain the Generational Hypothesis and describe how V8 uses it to optimize garbage collection.

Answer: The Generational Hypothesis states that most objects die young (they are allocated for temporary functions and quickly become unreachable).
V8 uses this to split the heap into two generations:
New Space (Young Generation): Stores new, short-lived objects. Freeing this space uses a fast Scavenger sweep that moves surviving objects to an active page and clears the old page.
Old Space (Old Generation): Stores long-lived objects that survived multiple scavenger sweeps. Freeing this space uses the slower Mark-Sweep-Compact algorithm. This ensures that the engine spends less time cleaning long-lived objects, improving performance.

12. Production Considerations

  • Avoid Memory Churn: Avoid allocating temporary objects in animation loop callbacks or high-frequency event handlers. Recycle objects using object pools to keep scavenger sweeps short.