Sub topic 16
Memory Retention and Performance Considerations
This chapter assumes you already know how closures capture variables (not snapshots) and how closures are used in callbacks and event handlers. A closure keeps its outer variables alive for as long as the closure itself is reachable. Usually that is exactly what you want. Sometimes it holds on to far more memory than you meant to keep.
Why Captured Variables Stay in Memory
The garbage collector frees a value only when no reachable code can still refer to it. A closure holds a reference to its lexical environment. Anything in that environment that the closure might read therefore stays alive. If the closure is registered as an event handler, stored in a cache, or attached to a long-lived object, the captured variables live just as long.
Capture Only What You Need
The handler below needs only the length of a large array. It copies that number into a small variable and refers to nothing else. Once attachHandler returns, nothing reaches bigData, so the engine can free it.
const target = new EventTarget();
function attachHandler(target) {
const bigData = new Array(1_000_000).fill('x');
const size = bigData.length;
target.addEventListener('click', () => {
console.log('Items:', size);
});
}
attachHandler(target);
target.dispatchEvent(new Event('click')); // Items: 1000000If the handler had logged bigData.length directly, the whole array would stay in memory for as long as the listener stays registered.
Gotcha: Closures Can Share One Environment
Engines such as V8 build one environment object per scope, and every closure created in that scope shares it. If any inner function references a variable, that variable goes into the shared environment, and every closure from that scope keeps it alive.
function setup() {
let bigData = new Array(1_000_000).fill('x');
const report = () => bigData.length; // references bigData
console.log('Loaded', report());
return () => 'hello'; // does not use bigData, but shares the environment
}
const greet = setup();
console.log(greet()); // 'hello', and bigData may still be retainedYou can fix this by setting bigData = null before returning, or by moving the large data into a separate function so it lives in a different scope.
Release Long-Lived Closures
Listeners, timers, and caches keep closures reachable until you remove them. Clean them up when they are no longer needed.
| Holder | How to release |
|---|---|
| Event listener | `removeEventListener` or an `AbortController` signal |
| `setInterval` | `clearInterval(id)` |
| Memoization cache | Clear or size-limit the `Map`, or use a `WeakMap` for object keys |
const target = new EventTarget();
const controller = new AbortController();
target.addEventListener('ping', () => console.log('pong'), {
signal: controller.signal
});
target.dispatchEvent(new Event('ping')); // pong
controller.abort(); // listener and its closure are released
target.dispatchEvent(new Event('ping')); // nothing loggedCommon Errors
- Referring to a large object inside a handler when you only need one field.
- Registering listeners or intervals and never removing them.
- Memoizing with an unbounded
Mapkeyed by inputs that never repeat.
Exercise
A function loads a 50 MB JSON object, starts a setInterval whose callback logs data.items.length every minute, and never clears the interval. What stays in memory, and how would you change the code so only the count is retained?
Show answer
The whole 50 MB object stays in memory, because the interval callback references data and the interval keeps the callback reachable forever. Copy the value first, const count = data.items.length;, and log count in the callback so data can be collected. Also store the interval ID and call clearInterval when the logging is no longer needed.