Sub topic 16
Memory Retention and Performance Considerations
This chapter assumes you already know the earlier material: what a closure is, that closures capture variables rather than values, and how closures are used in callbacks, timers, factory functions, and memoization. You should also know that JavaScript frees memory automatically through garbage collection. The examples run in Node.js 18 or later, and also in any modern browser console.
A closure keeps its lexical environment alive. That is useful because it is how private state works. It also costs memory: any variable a reachable closure can see stays in memory as long as that closure stays reachable. This chapter covers how that retention works, where it causes leaks, and when the cost of creating closures matters.
How Garbage Collection Sees a Closure
The garbage collector frees a value once nothing reachable refers to it. "Reachable" means a chain of references leads to the value from a root. Roots include the global object, the current call stack, and things the runtime itself holds, such as registered event listeners and pending timers.
A closure is an ordinary object. Through its hidden reference to the environment it was created in, it points at the captured variables. If the closure is reachable, those variables are reachable too.
Retention is the purpose of a closure, so it is not a leak in itself. A leak happens when a closure stays reachable after you stop needing it, or when it holds more data than it needs.
Capture Only What You Need
Here is the pattern from the Topic Spine, made runnable in Node with the built-in EventTarget:
function attachHandler(button) {
const bigData = new Array(1000000).fill('x');
const size = bigData.length;
button.addEventListener('click', () => {
console.log('Items:', size);
});
}
const button = new EventTarget();
attachHandler(button);
button.dispatchEvent(new Event('click')); // Items: 1000000The handler mentions only size. Once attachHandler returns, nothing refers to bigData, so the collector can free the array. The number stays alive for as long as the listener does.
Compare it with the version that reads the array inside the handler:
function attachHandlerLeaky(button) {
const bigData = new Array(1000000).fill('x');
button.addEventListener('click', () => {
console.log('Items:', bigData.length);
});
}
const button = new EventTarget();
attachHandlerLeaky(button);
button.dispatchEvent(new Event('click')); // Items: 1000000The output is the same. The difference is that the million-element array now lives as long as the listener, which may be the lifetime of the page.
The Shared Environment Gotcha
The language specification describes each closure as referring to its whole outer environment. Engines optimize this. V8, the engine in Chrome and Node, stores only the variables that some inner function actually uses in a heap-allocated context object. All closures created in the same scope share that one object.
This leads to a surprising leak:
function setup() {
const bigData = new Array(1000000).fill('x');
function logSize() {
return bigData.length; // references bigData
}
logSize();
return function greet() {
return 'hi'; // references nothing
};
}
const greet = setup();
console.log(greet()); // higreet never touches bigData. But logSize does, so V8 puts bigData in the shared context, and greet holds that context. As long as greet is reachable, the array is too, even though logSize is gone.
One fix is to drop the reference explicitly:
function setup() {
let bigData = new Array(1000000).fill('x');
const size = bigData.length;
bigData = null; // the shared context now holds null
return function greet() {
return `hi, ${size} items were processed`;
};
}
console.log(setup()()); // hi, 1000000 items were processedForgotten Listeners and Timers
The most common real leak is a closure that the runtime keeps reachable for you. A pending setInterval callback and a registered event listener are both roots. They stay alive until you cancel them.
function startPolling(onTick) {
let ticks = 0;
const id = setInterval(() => {
ticks += 1;
onTick(ticks);
}, 100);
return function stop() {
clearInterval(id);
};
}
const stop = startPolling((n) => console.log('tick', n));
setTimeout(stop, 350); // prints tick 1, tick 2, tick 3, then stopsIf you never call stop, the interval callback runs forever. It keeps ticks, onTick, and everything onTick captures alive, and it also keeps Node's process from exiting.
Listeners work the same way. To remove a listener, you need the same function reference you added, so store it:
function trackClicks(target) {
let clicks = 0;
const handler = () => {
clicks += 1;
console.log('clicks:', clicks);
};
target.addEventListener('click', handler);
return () => target.removeEventListener('click', handler);
}
const target = new EventTarget();
const untrack = trackClicks(target);
target.dispatchEvent(new Event('click')); // clicks: 1
untrack();
target.dispatchEvent(new Event('click')); // nothing printedAn AbortController lets you remove many listeners at once. Pass { signal: controller.signal } to each addEventListener call, then call controller.abort().
Unbounded Caches
A memoized function keeps its cache in a closure, so the cache lives as long as the function does. With unbounded input, the cache grows without limit. One fix is to cap the size of the cache:
function memoizeLimited(fn, maxSize = 100) {
const cache = new Map();
return function (n) {
if (cache.has(n)) {
return cache.get(n);
}
const result = fn(n);
cache.set(n, result);
if (cache.size > maxSize) {
const oldestKey = cache.keys().next().value; // Map keeps insertion order
cache.delete(oldestKey);
}
return result;
};
}
const square = memoizeLimited((n) => n * n, 2);
square(1);
square(2);
square(3); // evicts the entry for 1
console.log(square(3)); // 9, from cacheWhen the keys are objects, a WeakMap cache lets an entry disappear once its key object is no longer reachable anywhere else.
The Runtime Cost of Creating Closures
Each time a function expression is evaluated, the engine creates a new function object, and possibly a new context. That is cheap, but it is not free. It matters most in two places.
| Situation | Cost | Usual choice |
|---|---|---|
| Factory function creating a few objects | Negligible | Closures are fine |
| Factory creating many thousands of objects, each with several methods | One function object per method per instance | Consider a class or shared prototype methods |
| Creating a callback inside a hot loop | An allocation on every iteration | Hoist the function out of the loop if it captures nothing that changes |
| Long-lived handler capturing large data | Memory held for the handler's lifetime | Capture only small derived values |
The factory and class approaches compare like this:
function createPointClosure(x, y) {
return {
length() {
return Math.hypot(x, y);
}
};
}
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
length() {
return Math.hypot(this.x, this.y);
}
}
const a = createPointClosure(3, 4);
const b = new Point(3, 4);
console.log(a.length(), b.length()); // 5 5
console.log(createPointClosure(1, 1).length === createPointClosure(2, 2).length); // false
console.log(new Point(1, 1).length === new Point(2, 2).length); // trueEach closure-based point gets its own length function. All class instances share one function on Point.prototype. The closure version gives you real privacy. The class version uses less memory per instance. Modern classes can also get privacy with #private fields.
Finding Closure Leaks
Chrome DevTools and Node (node --inspect) let you take heap snapshots. A practical routine:
- Take a snapshot, perform the action you suspect leaks (open and close a dialog, for example), force garbage collection, and take another snapshot.
- Use the Comparison view to find object counts that grew.
- Select a leaked object and read its Retainers panel. A closure retainer appears as a
contextentry under a function name, which tells you which closure holds it.
Exercise
A function init() creates const rows = loadRows() (a large array), registers a window resize listener that calls render(rows.length), and returns nothing. The page runs for hours. What is retained, and how would you change the code so that only a number is retained?
Show answer
The resize listener is a root while it is registered. Its closure captures rows, so the whole array stays in memory for the life of the page. Compute const count = rows.length before registering the listener, use only count inside the handler, and make sure no other inner function in init refers to rows. Then the array can be collected after init returns.
Exercise
In the shared environment example, greet references nothing, yet bigData is retained in V8. Why, and name two fixes.
Show answer
V8 creates one context object for the scope that holds every variable any inner function uses. logSize uses bigData, so bigData sits in that shared context, and greet keeps the context alive. Fixes: set bigData to null after its last use, or move the work on bigData into a separate function so it never shares a scope with greet.
Exercise
You build 200,000 objects with a factory that defines four methods per object. Memory is high. What is the likely cause, and what is a lower-memory alternative?
Show answer
Each object gets four new function objects, for 800,000 functions, plus a context per object. Defining the methods once on a prototype (with a class, for example) makes all instances share four functions, and #private fields can keep privacy where it is needed.