
Garbage Collection Doesn't Prevent Memory Leaks
- كاتب موثّق
- ES2025
محتويات المقال
PriceChart objects are alive, each with its full array of price samples. Every chart that was ever closed is still in memory, and the code has a garbage collector the whole time.
The common misconception
free().
What actually happens
The collector frees what's unreachable, not what's unused
A JavaScript leak is a reference you forgot
window and document (their listeners), setInterval callbacks, module-level Maps and arrays used as caches, and anything those reach in turn.
The chart that never left
destroy() removes the canvas from the page and looks complete, but the constructor did two things and destroy() only undid one of them:
class PriceChart { points = Array.from({ length: 100_000 }, () => Math.random()); constructor(container) { this.el = document.createElement("canvas"); container.append(this.el); window.addEventListener("resize", () => this.redraw()); } redraw() { console.log(`redraw ${this.points.length} points`); } destroy() { this.el.remove(); // the canvas leaves the page, the listener stays }}const app = document.querySelector("#app");for (let i = 0; i < 200; i++) new PriceChart(app).destroy();class PriceChart { points = Array.from({ length: 100_000 }, () => Math.random()); #listeners = new AbortController(); constructor(container) { this.el = document.createElement("canvas"); container.append(this.el); window.addEventListener("resize", () => this.redraw(), { signal: this.#listeners.signal, }); } redraw() { console.log(`redraw ${this.points.length} points`); } destroy() { this.el.remove(); this.#listeners.abort(); // removes every listener added with this signal }}const app = document.querySelector("#app");for (let i = 0; i < 200; i++) new PriceChart(app).destroy();window keeps its resize listeners, the arrow function is a closure that holds this, and this holds the 100,000 points and the canvas element. The canvas is now a : removed from the page, but still referenced from JavaScript. Both files were run in headless Chromium 156, followed by a forced garbage collection through the DevTools protocol and a count of what was left. The wrong version kept all 200 charts alive, about 161 MB of JavaScript heap, and the next resize event logged redraw 200 times for charts nobody could see. The right version left no charts alive and a heap of about 1.2 MB.
signal option of addEventListener. MDN describes it plainly: the listener is removed when abort() is called on the AbortController that owns the signal. One controller per component lets destroy() remove every listener the component added, with one call and without keeping references to each handler.
Data about objects you don't own: WeakMap
Map from DOM elements to metadata keeps every element alive for as long as the map lives, even after the element leaves the page. A WeakMap doesn't: MDN explains that its keys don't prevent garbage collection, and once a key is collected, its value can be collected too.
const tooltipFor = new WeakMap(); // not new Map()function attachTooltip(element, text) { tooltipFor.set(element, { text, shownAt: null });}// Once `element` is unreachable everywhere else, its entry// can be collected too. A Map would keep both alive forever.WeakMap's keys or count them, because that would expose when garbage collection runs. If you need to iterate, you need a Map with explicit deletes or a size limit.
window or document | signal and call abort(), or remove the same function | |
setInterval callback | clearInterval in your cleanup | |
Map or array cache | WeakMap | |
How to apply it in your project
Pair every subscription with its cleanup For each addEventListener,setInterval, observer or subscription in a component, find the line that undoes it. A component-wideAbortControllermakes listener cleanup one call.Give every cache a limit Any Map, array or object that grows at module scope needs a maximum size, an expiry, or object keys in aWeakMap.Hold DOM elements only as long as they're on the page When a component removes an element, set the fields that point at it to null, or keep them inside the component that gets destroyed along with it.Test the loop, not the page load Leaks show up after repetition. Script the action you suspect, run it many times, click the Collect garbage button in DevTools, and compare memory with where you started.
Key takeaways
The garbage collector frees what's unreachable; anything your code can still reach stays, needed or not. A JavaScript memory leak is a long-lived object, often window, a timer or a module-level cache, holding a reference you forgot.Every listener, timer and subscription needs a cleanup; AbortControllersignals make listener cleanup one call.Use WeakMapfor data attached to objects you don't control, and cap every other cache.Don't count on WeakRefor finalizers; confirm a fix with repeated actions, a forced GC and a heap snapshot.
التعليقات (0)