Sub topic 10
Finding memory leaks with heap snapshots
This chapter assumes you can open DevTools and use the Console and Performance panels. You should also know basic JavaScript, including closures and event listeners. It covers the Memory panel, which records what is held in memory at one moment and lets you compare moments.
What a leak is
JavaScript frees memory through garbage collection. The collector removes any object that the page can no longer reach from a root, such as the global window object or a running function's variables. A leak happens when your code keeps a reference to data it no longer needs. The collector must keep anything that is still reachable, so the memory never returns.
Typical causes are:
- A global array or map that only grows, such as a cache with no size limit.
- Event listeners that are added but never removed.
- Timers (
setInterval) that keep running after the feature is gone. - Detached DOM nodes, which are elements removed from the page but still referenced by a variable.
Symptoms are a page that slows down over a long session, or a tab that crashes. The Performance panel can show a memory graph that climbs and never drops. The Memory panel tells you which objects are responsible.
A leaking page
This script keeps a new large array reachable on every click.
const cache = [];
document.addEventListener('click', () => {
// Each click keeps another 1 MB array reachable through cache.
cache.push(new Array(1_000_000).fill('x'));
});Nothing ever removes entries from cache, and cache is a global, so every array stays reachable.
The three-snapshot workflow
A heap snapshot lists every object in memory with its size and the objects that hold it. One snapshot alone is hard to read. The useful technique is to compare snapshots taken before and after the suspect action.
- Open DevTools and choose the Memory panel.
- Select Heap snapshot and click Take snapshot. Run the action once first so that one-time setup, such as lazy initialization, is already finished.
- Click Collect garbage (the trash can icon) to remove unreachable objects, then take the first snapshot.
- Repeat the action several times. For the example page, click ten times.
- Click Collect garbage again and take a second snapshot.
- Select the second snapshot and change the view from Summary to Comparison. Choose the first snapshot as the base.
- Sort by Size Delta or # Delta. Rows with large positive deltas are growing.
Collecting garbage first matters. Without it, the comparison includes objects that were already unreachable and would have disappeared on their own, which produces false leads.
Reading the comparison
In the example, the comparison shows a large positive delta for (array) and for the strings or numbers inside it. The columns mean the following.
| Column | Meaning |
|---|---|
| Constructor | The type or class of the objects in the group |
| # New / # Deleted / # Delta | Objects created, freed, and the net change since the base snapshot |
| Alloc. Size / Freed Size / Size Delta | The same counts in bytes |
| Shallow Size | Memory held by the object itself, not by what it references |
| Retained Size | Memory that would be freed if this object were removed |
Retained size is usually the better number for finding leaks. A small object, such as the cache array, can retain hundreds of megabytes through the objects it points to.
Finding who holds the object
Click one of the growing objects. The Retainers pane at the bottom shows the chain of references from a root to that object. Read it from the object upward until you reach something you wrote, such as a variable name or a function.
For the example, the chain ends at cache in the global scope. That tells you the fix: limit or clear the collection.
const cache = [];
const MAX_ENTRIES = 5;
document.addEventListener('click', () => {
cache.push(new Array(1_000_000).fill('x'));
if (cache.length > MAX_ENTRIES) {
cache.shift(); // drop the oldest entry so it can be collected
}
});Repeat the three-snapshot workflow. The size delta should now stay near zero after the cache fills.
Detached DOM nodes
Type Detached in the snapshot's class filter box. Any element listed there is out of the document but still referenced, often by a closure or an event handler. The Retainers pane shows which variable holds it. Removing the reference, for example by setting it to null or calling removeEventListener, lets the collector free it.
Common mistakes
- Taking a single snapshot and looking for "the big thing". Large objects are often legitimate. Growth between snapshots is the signal.
- Skipping the garbage collection step before each snapshot.
- Testing the action only once. A small leak can hide in noise, so repeat it enough times to see a clear trend.
- Treating a rising memory graph as proof of a leak. Memory can grow temporarily until the collector runs.
Exercise
You take two heap snapshots 20 clicks apart. In Comparison view, a group of objects shows a Size Delta of +18 MB. Which pane do you use next to find the code that keeps them in memory, and what does it show?
Show answer
Select one of the objects and read the Retainers pane. It shows the chain of references from a root, such as the global object, down to that object. The first variable or function in the chain that you wrote is what keeps the objects reachable, so that is where you change the code.
Exercise
Why should you click Collect garbage before taking each snapshot?
Show answer
Collecting garbage removes objects that are already unreachable. Without it, those objects appear in the snapshot and the comparison, which can make normal temporary allocations look like a leak.