Sub topic 10
Finding memory leaks with heap snapshots
This chapter assumes you can open DevTools (chapter 1), read the Performance panel basics, and write basic JavaScript with event listeners and closures. It explains what a memory leak is in a garbage-collected language, how to confirm one, and how to find the object that is holding memory using the Memory panel.
What a leak is in JavaScript
JavaScript frees memory automatically. The garbage collector (GC) is the part of the engine that finds objects the program can no longer reach and releases them. An object is reachable if you can get to it by following references from a root. Roots include global variables, the currently running call stack, and the DOM.
A memory leak in JavaScript is an object your code no longer needs but that is still reachable. The GC cannot free it because something still points to it. The leak is therefore a reference you forgot to remove, not memory the engine lost track of.
Common sources of unwanted references:
- Global variables and long-lived arrays, maps or caches that only grow.
- Event listeners that are added but never removed.
- Timers (
setInterval) whose callbacks capture large objects. - Closures that keep a whole scope alive.
- Detached DOM nodes: elements removed from the page but still referenced by a variable.
Here is the example used in this chapter. Each click adds a 1 MB array to a list that nothing ever empties.
const cache = [];
document.addEventListener('click', () => {
// Each click keeps another 1 MB array reachable through cache.
cache.push(new Array(1_000_000).fill('x'));
});The cache array is a global root. Every array pushed into it stays reachable for as long as the page lives.
Confirm that memory is growing
Do not start with a snapshot. First check that there is a leak. Memory that rises and then falls after a GC is normal.
Two quick ways to check:
- Open the Performance panel, enable the Memory checkbox, and record while you repeat the suspect action. A leak shows the JS heap line climbing in a staircase pattern that never returns to its starting level. A healthy page shows a sawtooth: it rises, then drops when the GC runs.
- Open the Performance monitor (Command menu, then "Show Performance monitor") to watch JS heap size and DOM node count live. A DOM node count that keeps rising points to detached nodes or listeners.
Before you test, click the trash can icon (Collect garbage) in the Memory or Performance panel. This forces a GC so that you measure what is really retained.
The Memory panel's three profiling types
Open DevTools and choose the Memory panel. It offers these profiling types:
| Profile type | What it records | Use it when |
|---|---|---|
| Heap snapshot | A complete picture of all objects in memory at one moment | You want to find what is retained and why |
| Allocation instrumentation on timeline | Allocations over time, with the stack that created them | You need to know which code allocates the objects |
| Allocation sampling | A low-overhead statistical sample of allocations by function | You want a cheap overview on a long run |
This chapter focuses on heap snapshots because they answer the most common question: what is still in memory, and what is holding it?
The three-snapshot technique
Comparing snapshots is more reliable than reading one. A single snapshot contains thousands of objects that belong to the browser and your framework. The difference between two snapshots shows what your action added.
Follow this workflow with the click example:
- Load the page and click the Collect garbage button.
- In the Memory panel, select Heap snapshot and click Take snapshot. This is Snapshot 1, the baseline.
- Click on the page several times. Use a fixed number, such as five, so the expected growth is easy to predict.
- Click Collect garbage, then take Snapshot 2.
- Repeat the same five clicks, collect garbage, and take Snapshot 3.
Doing the action once before the baseline is also a good habit. The first run often creates one-time objects such as caches and lazily initialized modules, which are not leaks.
In the example, each click adds one array of about 1 MB, so each snapshot should be roughly 5 MB larger than the one before. The snapshot size shown in the left list confirms the growth.
Reading a snapshot
Select a snapshot, then use the view drop-down at the top of the panel. There are four views.
Summary
Summary groups objects by constructor name, for example Array, (string) or HTMLDivElement. Key columns:
- Shallow Size: the memory held by the object itself, not counting what it references.
- Retained Size: the memory that would be freed if this object were deleted. It includes everything that is only reachable through it.
- Distance: the shortest number of reference hops from a GC root.
Sort by Retained Size to find the biggest holders. Retained size is usually more useful than shallow size, because a small object can retain a very large structure.
Comparison
Comparison is the view for leak hunting. Select Snapshot 3 and, in the "Compared to" drop-down, choose Snapshot 2. Each row now shows:
# New: objects created since the earlier snapshot and still alive.# Deleted: objects from the earlier snapshot that were freed.# Delta: new minus deleted.Alloc. SizeandFreed Size, andSize Delta.
A leak appears as a constructor with a positive, steady delta and a large size delta. In the example, the Array row shows a delta of +5 and a size delta of about 40 MB, because the array of one million elements uses 8 bytes per slot for a total of about 8 MB. Treat that figure as an estimate. The exact size depends on the engine's internal element representation.
Containment
Containment shows the object graph starting from the roots, such as the global window object. It is useful for browsing, but it is a poor starting point for finding leaks.
Statistics
Statistics shows a pie chart of memory by category: code, strings, JS arrays, typed arrays and system objects. It tells you what kind of data dominates, not who owns it.
Finding what holds the object
Finding the leaking object is half the job. You must also find the reference that keeps it alive.
- In the Comparison view, expand the
Arrayrow and select one of the new instances. - Look at the Retainers pane at the bottom of the panel. It shows the chain of references leading from a GC root to the selected object.
- Read the chain from the bottom up. The bottom entry is the root, and each line above it is an object holding the next.
For the example, the chain looks like this:
Array @12345
in system / Array @6789 (index 3)
in cache in Window / https://example.comThe chain says that the global cache variable on window holds an array, and that array holds the selected array at index 3. The fix is now clear: bound the size of cache, or stop storing the data.
Some details to know when reading retainers:
- Entries in grey or in parentheses, such as
(system), are engine internals. Look for the first entry that belongs to your code. - A name like
context in function()means a closure holds the object. Click the function to open its source location. - Weak references (
WeakMap,WeakRef) do not appear as strong retainers, because they do not keep an object alive.
Detached DOM nodes
Detached nodes are a frequent leak in single-page applications. A node is detached when it has been removed from the document but is still referenced by JavaScript. It is not drawn, but it and its whole subtree stay in memory.
let detached;
document.addEventListener('click', () => {
const panel = document.createElement('div');
panel.textContent = 'temporary panel';
document.body.appendChild(panel);
document.body.removeChild(panel);
detached = panel; // removed from the page, still referenced
});In a snapshot, type Detached into the Class filter. DevTools lists entries such as Detached HTMLDivElement. Select one and read its retainers to find the variable or listener that holds it. Note that this example holds only the most recent panel, so it does not grow. A leak that grows would push each panel into an array or attach a listener per node.
Common mistakes
- Not forcing garbage collection. Uncollected garbage looks like a leak. Click Collect garbage before each snapshot.
- Taking one snapshot only. A single snapshot cannot show growth. Compare at least two.
- Changing the action between snapshots. Repeat exactly the same steps, or the delta is meaningless.
- Ignoring extensions. Browser extensions add their own objects. Test in an Incognito window with extensions disabled, or use a clean profile.
- Chasing small deltas. A few objects of difference can be caches warming up. Look for a delta that scales with the number of repetitions.
- Reading shallow size alone. The real cost is in retained size.
- Profiling a minified build. Names become unreadable. Use a development build or source maps where possible.
Snapshots also have a cost. Taking one pauses the page, and a large heap can take many seconds and a lot of memory in the DevTools process. Expect the page to freeze while it runs.
A repeatable workflow
- Notice a symptom: slowing page, growing tab memory, or a rising JS heap in the Performance monitor.
- Confirm growth with the Performance panel's Memory checkbox.
- Reproduce the suspect action in a loop with a fixed count.
- Take a baseline snapshot, repeat, then take two more with garbage collection before each.
- Use Comparison to find a constructor whose delta scales with repetitions.
- Open a new instance and read its Retainers to find the reference.
- Fix the code, then repeat the test to confirm the delta drops to zero.
The last step matters. A fix is not verified until the same snapshot comparison shows no growth.
Exercise
You take Snapshot 1, click a button 10 times, and take Snapshot 2. The Comparison view shows a +10 delta for Detached HTMLDivElement. What does this tell you, and what do you do next?
Show answer
Ten removed DOM elements are still reachable from JavaScript, one per click, so the number scales with your action and is likely a leak. Select one instance and read the Retainers pane to find the variable, array or event listener that holds it. Then remove that reference (for example, clear the array or call removeEventListener when the element is removed), and repeat the test to check that the delta falls to zero. Collect garbage before each snapshot so uncollected nodes do not distort the count.
Exercise
Why is Retained Size usually more useful than Shallow Size when hunting a leak?
Show answer
Shallow size counts only the memory of the object itself. Retained size counts everything that would be freed if the object were removed, including objects reachable only through it. A small object, such as an array holding references to many large objects, can have a tiny shallow size and a huge retained size, and the retained size is what you would recover by fixing the leak.