Hello! Welcome to the first lesson in our module on Memory Management and Performance Profiling.
Throughout this course, we're diving deep into the advanced mechanics of JavaScript. So far, we've explored various language features and patterns. Now, we shift our focus to the runtime environment itself, starting with a fundamental process that makes high-level languages like JavaScript possible: automatic memory management.
In this lesson, you will learn to explain the mark-and-sweep algorithm used by JavaScript's garbage collector. Understanding this core process is not just an academic exercise; it's the theoretical foundation you'll need to diagnose memory leaks and optimize your application's performance, which we'll cover in subsequent lessons.
The Problem: Automatic Memory Management
In languages like C or C++, you are responsible for manually allocating memory for your data structures and, crucially, deallocating that memory when you're done with it. Forgetting to deallocate memory leads to memory leaks, and deallocating memory that's still in use leads to crashes.
JavaScript frees you from this burden by employing a process called garbage collection (GC). The JavaScript engine's garbage collector periodically runs in the background, automatically identifying and freeing up memory that is no longer needed by the program.
But how does it know what's "no longer needed"? The answer lies in a concept called reachability.
Reachability: The Core Principle
An object is kept in memory only if it is "reachable"—meaning the program can still access it. The garbage collector starts its search from a set of known, always-accessible references called roots.
The primary roots are:
- Global variables: Any object referenced by a global variable (e.g.,
windowin a browser orglobalin Node.js). - The Call Stack: Local variables and function parameters in all currently executing functions.
- Active Closures: Variables from an outer scope that are "closed over" by an inner function that is still reachable.
Any object that can be reached by following a chain of references starting from one of these roots is considered "alive." Any object that cannot be reached is considered "garbage."
To get a solid grasp of this foundational concept, please read the first two sections of the following article.
JavaScript Garbage Collection - 33 JavaScript Concepts
This article from '33 JavaScript Concepts' provides a clear, concise explanation of garbage collection, reachability, and the roots from which the process begins.
Please read the sections 'What is Garbage Collection?' and 'How Does JavaScript Know What’s Garbage?'. Focus on the definition of 'roots' and how the engine traces reference chains to determine if an object is alive or garbage.
The Mark-and-Sweep Algorithm
Now that we understand the goal is to find all unreachable objects, how is this actually implemented? All modern JavaScript engines use an algorithm called mark-and-sweep. As the name implies, it works in two main phases.
Given your background in computer science, you can think of the objects and their references in memory as a directed graph, where objects are nodes and references are edges. The roots are the entry points to this graph.
Phase 1: Marking
The goal of this phase is to find and "mark" all live objects. The algorithm works like this:
- Start with the root nodes (globals, call stack, etc.).
- Traverse the entire object graph, following every reference from the roots.
- Every object visited during this traversal is marked as "live."
This is essentially a graph traversal problem, similar to a Breadth-First Search (BFS) or Depth-First Search (DFS). To manage the state of the traversal, garbage collectors often use a tri-color abstraction:
- White: The initial state of all objects. Any object that is still white at the end of the marking phase is garbage.
- Gray: An object that has been discovered (reached) but whose child references have not yet been fully processed. These objects are in a queue to be scanned.
- Black: An object that has been discovered, and all of its references have been followed and processed. This object is confirmed to be "live."
The marking phase is complete when the set of gray objects is empty.
To see a great visual explanation of this process, please watch the following video segment.
Garbage Collection Algorithms: Mark Sweep, Generation Hypothesis and JIT code injection
Gaurav Sen provides an excellent, engineer-focused explanation of the mark-and-sweep algorithm using the tri-color abstraction and a graph traversal analogy.
Watch the segment from 00:59 to 01:55, which details the tri-color algorithm and how it's used to identify live objects through a graph traversal.
Phase 2: Sweeping
Once the marking phase is complete, the memory heap contains a mix of marked ("live") and unmarked ("garbage") objects. The sweep phase is straightforward:
- The garbage collector scans the entire heap from start to finish.
- If an object is not marked as "live" (i.e., it's still "white"), its memory is reclaimed. It can be added to a "free-list" to be used for future allocations, or the memory can be managed in other ways.
- The marks on the live objects are cleared, resetting them to "white" for the next GC cycle.
The following text provides a step-by-step summary and a helpful diagram of the full mark-and-sweep process.
JavaScript Garbage Collection - 33 JavaScript Concepts
Let's return to the '33 JavaScript Concepts' article to solidify our understanding of the two phases and see how this algorithm handles a common challenge.
Read the sections 'The Mark-and-Sweep Algorithm' and 'Reference Counting: A Failed Approach'. Pay close attention to the diagram illustrating the process and the explanation of why mark-and-sweep elegantly handles circular references, a problem that plagued older GC algorithms.
Test your understanding!
Consider the following code snippet. After the final line executes, which objects are eligible for garbage collection?
let character = {
name: 'Lelouch',
geass: { type: 'The Power of Kings' }
};
let rebellion = {
leader: character,
name: 'The Black Knights'
};
let zero = character;
// The program continues...
character = null;
rebellion.leader = null;
Show answer
Neither object will be garbage collected.
Here's why:
- The object
{ name: 'Lelouch', ... }is still reachable through thezerovariable, which is a root (a global variable). - The object
{ name: 'The Black Knights', ... }is still reachable through therebellionvariable, which is also a root. - Even though the link from
rebelliontocharacterwas severed (rebellion.leader = null), both core objects remain reachable from global scope.
To make them eligible for collection, all root references would have to be nullified (e.g., zero = null; rebellion = null;).
Optimizations in V8: Mark-Sweep-Compact
A simple mark-and-sweep that pauses program execution (a "stop-the-world" event) to scan the entire heap can be very slow, leading to noticeable freezes in an application. Modern engines like V8 (used in Chrome and Node.js) employ sophisticated optimizations based on the Generational Hypothesis, which observes that "most objects die young."
This leads to the heap being divided into two main areas:
- Young Generation: Where new objects are allocated. This area is small and collected frequently in a fast process called a Minor GC (or Scavenge). Most objects are created and become garbage here without ever aging.
- Old Generation: For objects that survive one or more Minor GCs. This area is much larger and is collected less frequently by a Major GC.
The Major GC in V8 uses an optimized version of mark-and-sweep called Mark-Sweep-Compact.
- Marking: The marking is done incrementally. The GC does a small amount of marking work and then yields back to the main thread, allowing the application to run. It repeats this until all live objects are marked. This prevents long, blocking pauses.
- Sweeping: After marking, the memory of dead objects is reclaimed. This can often be done concurrently in a background thread without pausing the main JavaScript thread.
- Compaction: Sweeping can leave the memory fragmented, with live objects scattered among free space. To combat this, V8 will periodically perform compaction, which involves moving live objects together into a contiguous block of memory. This reduces fragmentation and improves allocation speed.
The following video from a Node.js conference provides a deeper look into how V8's garbage collectors for both the Young and Old Generations work, specifically detailing the mark-sweep and compacting phases.
Are Your V8 Garbage Collection Logs Speaking To You? by Joyee Cheung, Alinode(Alibaba)
This talk by Joyee Cheung, a Node.js core contributor, provides a technical overview of V8's generational garbage collector, focusing on the scavenge algorithm for the young generation and the mark-sweep-compact algorithm for the old generation.
Watch the segments covering the generational hypothesis (07:13 - 09:38), the Scavenge algorithm for the new generation (10:25 - 11:27), and finally the Mark-Sweep algorithm for the old generation (11:27 - 12:27). Focus on how the old generation is managed with marking, sweeping (using free lists), and compacting.
Diagram of the generational heap in V8
This diagram from the '33 JavaScript Concepts' article illustrates the division of the heap into a Young Generation for new objects and an Old Generation for long-lived objects. The Mark-and-Sweep algorithm we've studied is primarily used in the more complex and less frequent collection of the Old Generation.
Test your understanding!
Why is the "generational hypothesis" so effective for optimizing garbage collection performance?
Show answer
The generational hypothesis is effective because it allows the garbage collector to focus its effort where it's most likely to be productive.
By separating objects into a "young" and "old" generation, the GC can:
- Run very frequent and fast collections on the small Young Generation, where the vast majority of objects are created and quickly become garbage. This reclaims a lot of memory with minimal performance cost.
- Avoid repeatedly scanning long-lived objects in the Old Generation. Since these objects have already survived at least one collection, they are likely to survive again. Collecting this generation less frequently saves significant processing time.
This strategy results in shorter and less frequent GC pauses overall, leading to a more responsive application.
Conclusion
In this lesson, we demystified the process of automatic memory management in JavaScript. We established that the core principle is reachability from a set of roots.
Here are the key takeaways:
- The mark-and-sweep algorithm is the standard for modern JavaScript engines.
- It operates in two phases: Marking (traversing the object graph to find all live objects) and Sweeping (reclaiming memory from unmarked, or garbage, objects).
- This algorithm correctly handles circular references, which were a major problem for older reference-counting algorithms.
- Engines like V8 heavily optimize this process using a generational collector that separates objects into Young and Old generations, applying different collection strategies to each.
- The Major GC for the Old Generation uses a Mark-Sweep-Compact variant with incremental and concurrent techniques to minimize application pauses.
In our next lesson, we will put this theory into practice. You'll learn how to use browser DevTools to take and analyze heap snapshots, which will allow you to visualize the object graph we've discussed and begin hunting for memory leaks in a real application.