Common Memory Leaks
Common Memory Leaks
Section titled “Common Memory Leaks”Introduction
Section titled “Introduction”These patterns create references that prevent garbage collection even when the objects are no longer needed.
1. Accidental Globals
Section titled “1. Accidental Globals”function bad() { leak = 'global'; // ❌ No declaration → global scope this.alsoLeak = 'global'; // ❌ 'this' is global in non-strict}2. Forgotten Closures
Section titled “2. Forgotten Closures”const heavy = new Array(1000000);const btn = document.getElementById('btn');
// ❌ The closure holds 'heavy' as long as 'btn' existsbtn.addEventListener('click', () => { console.log(heavy); // heavy can't be GC'd});
// ✅ Only reference what's neededbtn.addEventListener('click', () => { console.log('clicked!'); // no large reference});3. Detached DOM Nodes
Section titled “3. Detached DOM Nodes”let element = document.getElementById('temp');document.body.appendChild(element);document.body.removeChild(element);// element variable still holds reference → not GC'd!element = null; // Now it can be collected4. Outdated References
Section titled “4. Outdated References”const cache = new Map();function processUser(user) { cache.set(user.id, user); // If user is deleted, cache still holds the reference}
// ✅ Use WeakMap for auto-cleanupconst betterCache = new WeakMap();5. Forgotten Subscriptions
Section titled “5. Forgotten Subscriptions”class Store { constructor() { this.subscribers = new Set(); } subscribe(callback) { this.subscribers.add(callback); // ✅ Return unsubscribe function return () => this.subscribers.delete(callback); }}Detection
Section titled “Detection”- Chrome DevTools → Memory tab → Heap Snapshots
- Look for “Detached DOM nodes”
- Record allocation timeline
- Compare snapshots before/after actions
Summary
Section titled “Summary”- Most leaks are caused by lingering references
- Closures, event listeners, and subscriptions are common culprits
- Always clean up with cleanup/unsubscribe patterns
- Use WeakMap/WeakSet for object-associated data
- Heap snapshots in DevTools help find leaks