JavaScript and TypeScript course Β· Module 10: TypeScript in Practice
Memory Management - Garbage Collection, Memory Leaks
In this lesson6
Imagine a paddock that nobody ever clears of leftover feed. For a few days nothing shows, but after a month the T-Rex has nowhere to stand. That is how a memory leak works: the application keeps data it no longer needs and gets slower by the hour. Memory management is one of the most important aspects of performance. Even though JavaScript has an automatic garbage collector, you need to understand how memory works to avoid leaks.
How Memory Works in JavaScript
Memory Lifecycle
Every value goes through three stages: allocation, use and release. You see the first two in your code, and the third is done for you by the garbage collector (GC):
// Memory lifecycle in JavaScript
const memoryLifecycle = {
// 1. Memory allocation - automatic
allocation: () => {
const obj = { name: 'John', age: 30 }; // Allocation in heap
const arr = [1, 2, 3, 4, 5]; // Allocation in heap
const num = 42; // Allocation in stack (primitive)
return { obj, arr, num };
},
// 2. Memory usage - read/write
usage: (data) => {
data.obj.name = 'Jane'; // Using allocated memory
data.arr.push(6);
console.log(data.obj, data.arr);
},
// 3. Memory release - automatic by GC
release: () => {
// When variables go out of scope, they become candidates for GC
// GC will run automatically at the appropriate time
}
};
// Demonstration of the cycle
function demonstrateMemoryLifecycle() {
const data = memoryLifecycle.allocation(); // Allocation
memoryLifecycle.usage(data); // Usage
// After the function ends, 'data' becomes a candidate for GC
}
demonstrateMemoryLifecycle();You never call any free(). When data stops being reachable after the function ends, the object becomes a candidate for cleanup, and the GC picks the moment.
Stack vs Heap
It is often said that primitives live on the stack and objects on the heap:
// Stack - stores primitives and references
function stackExample() {
const a = 5; // Stack
const b = 'hello'; // Stack (reference to string in heap)
const c = true; // Stack
console.log('Stack variables:', a, b, c);
} // After the function ends, everything from stack is removed
// Heap - stores objects and arrays
function heapExample() {
const obj = { x: 1, y: 2 }; // Object in heap, reference in stack
const arr = [1, 2, 3]; // Array in heap, reference in stack
// Modifying object in heap
obj.z = 3;
arr.push(4);
return { obj, arr }; // Returning references
} // References from stack are removed, but objects in heap remain
// Memory allocation visualization
class MemoryVisualizer {
constructor() {
this.allocations = [];
this.currentId = 0;
}
allocate(type, size, description) {
const allocation = {
id: this.currentId++,
type: type, // 'stack' | 'heap'
size: size,
description: description,
timestamp: Date.now(),
freed: false
};
this.allocations.push(allocation);
console.log(`Allocated ${type}: ${description} (${size} bytes)`);
return allocation.id;
}
free(id) {
const allocation = this.allocations.find(a => a.id === id);
if (allocation) {
allocation.freed = true;
allocation.freedAt = Date.now();
console.log(`Freed: ${allocation.description}`);
}
}
getMemoryStats() {
const active = this.allocations.filter(a => !a.freed);
const freed = this.allocations.filter(a => a.freed);
return {
totalAllocations: this.allocations.length,
activeAllocations: active.length,
freedAllocations: freed.length,
totalActiveSize: active.reduce((sum, a) => sum + a.size, 0),
memoryLeaks: active.filter(a => Date.now() - a.timestamp > 30000) // > 30s
};
}
}
const memoryViz = new MemoryVisualizer();
// Usage example
function demonstrateMemoryAllocation() {
// Stack allocations
const stackId1 = memoryViz.allocate('stack', 8, 'number variable');
const stackId2 = memoryViz.allocate('stack', 8, 'string reference');
// Heap allocations
const heapId1 = memoryViz.allocate('heap', 64, 'object {name, age, city}');
const heapId2 = memoryViz.allocate('heap', 32, 'array [1,2,3,4,5]');
// Simulating memory release
setTimeout(() => {
memoryViz.free(stackId1);
memoryViz.free(stackId2);
console.log('Memory stats:', memoryViz.getMemoryStats());
}, 1000);
setTimeout(() => {
memoryViz.free(heapId1);
// heapId2 is not freed - simulating a memory leak
console.log('Final memory stats:', memoryViz.getMemoryStats());
}, 2000);
}This is a simplified model. The ECMAScript specification does not define where values live in memory, so the engine decides: for example, strings and variables captured by closures end up on the heap. MemoryVisualizer only simulates allocations, but it shows well what a leak is: an entry that nobody ever frees.
Garbage Collection in JavaScript
Types of GC Algorithms
Compare two strategies. Reference counting removes an object when nothing points to it. Mark-and-sweep starts from the roots, such as global variables and the call stack, marks everything reachable from them and removes the rest:
// 1. Reference Counting (old algorithm)
class ReferenceCountingDemo {
constructor() {
this.objects = new Map();
}
createObject(id, data) {
const obj = {
id: id,
data: data,
refCount: 1,
references: []
};
this.objects.set(id, obj);
console.log(`Created object ${id} with ref count: 1`);
return obj;
}
addReference(fromId, toId) {
const fromObj = this.objects.get(fromId);
const toObj = this.objects.get(toId);
if (fromObj && toObj) {
fromObj.references.push(toId);
toObj.refCount++;
console.log(`Object ${toId} ref count increased to: ${toObj.refCount}`);
}
}
removeReference(fromId, toId) {
const fromObj = this.objects.get(fromId);
const toObj = this.objects.get(toId);
if (fromObj && toObj) {
const index = fromObj.references.indexOf(toId);
if (index > -1) {
fromObj.references.splice(index, 1);
toObj.refCount--;
console.log(`Object ${toId} ref count decreased to: ${toObj.refCount}`);
// Auto GC when ref count reaches 0
if (toObj.refCount === 0) {
this.collectObject(toId);
}
}
}
}
collectObject(id) {
const obj = this.objects.get(id);
if (obj) {
// Recursively decrease reference counts
obj.references.forEach(refId => {
this.removeReference(id, refId);
});
this.objects.delete(id);
console.log(`Collected object ${id}`);
}
}
// Problem: Circular references
createCircularReference() {
const obj1 = this.createObject('circular1', 'First object');
const obj2 = this.createObject('circular2', 'Second object');
// Mutual references - memory leak in reference counting!
this.addReference('circular1', 'circular2');
this.addReference('circular2', 'circular1');
console.log('Created circular reference - will never be collected!');
return { obj1, obj2 };
}
}
// 2. Mark and Sweep (modern algorithm)
class MarkAndSweepDemo {
constructor() {
this.objects = new Map();
this.roots = new Set(); // Global variables, stack references
}
createObject(id, data) {
const obj = {
id: id,
data: data,
references: [],
marked: false
};
this.objects.set(id, obj);
return obj;
}
addToRoots(id) {
this.roots.add(id);
console.log(`Added ${id} to GC roots`);
}
removeFromRoots(id) {
this.roots.delete(id);
console.log(`Removed ${id} from GC roots`);
}
addReference(fromId, toId) {
const fromObj = this.objects.get(fromId);
if (fromObj && !fromObj.references.includes(toId)) {
fromObj.references.push(toId);
}
}
// Mark phase - marks all reachable objects
markPhase() {
console.log('Starting mark phase...');
// Clear previous marks
this.objects.forEach(obj => obj.marked = false);
// Mark all objects reachable from roots
const visited = new Set();
const markRecursive = (id) => {
if (visited.has(id)) return;
visited.add(id);
const obj = this.objects.get(id);
if (obj) {
obj.marked = true;
console.log(` Marked object ${id}`);
// Recursively mark references
obj.references.forEach(refId => markRecursive(refId));
}
};
// Start from all roots
this.roots.forEach(rootId => markRecursive(rootId));
}
// Sweep phase - removes unmarked objects
sweepPhase() {
console.log('Starting sweep phase...');
const toDelete = [];
this.objects.forEach((obj, id) => {
if (!obj.marked) {
toDelete.push(id);
}
});
toDelete.forEach(id => {
console.log(`Collecting object ${id}`);
this.objects.delete(id);
});
console.log(`Collected ${toDelete.length} objects`);
}
// Full GC cycle
runGarbageCollection() {
console.log('Running garbage collection...');
this.markPhase();
this.sweepPhase();
console.log(`Active objects: ${this.objects.size}`);
}
// Demonstration of resolving circular references
demonstrateCircularReferences() {
// Creating objects with circular references
const obj1 = this.createObject('mark1', 'Object 1');
const obj2 = this.createObject('mark2', 'Object 2');
const obj3 = this.createObject('mark3', 'Object 3');
// Circular references
this.addReference('mark1', 'mark2');
this.addReference('mark2', 'mark3');
this.addReference('mark3', 'mark1'); // Circular!
// Only obj1 is in roots
this.addToRoots('mark1');
console.log('Before GC - objects with circular references');
this.runGarbageCollection(); // All will be marked as reachable
// Remove from roots
this.removeFromRoots('mark1');
console.log('After removing from roots');
this.runGarbageCollection(); // All will be collected despite circular references!
}
}Two objects pointing at each other will fool reference counting, but not mark-and-sweep: when no root leads to them, both disappear. That is why modern engines use mark-and-sweep, and a reference cycle by itself is no longer a leak. After the mark and sweep phases the engine can also compact memory to remove the gaps.
Generational Garbage Collection
Most objects live briefly, so engines split the heap into generations. The young one is cleaned often and quickly, and objects that survive a few cycles move to the old one:
// Modern JS engines use generational GC
class GenerationalGCDemo {
constructor() {
// Different generations of objects
this.youngGeneration = new Map(); // New objects
this.oldGeneration = new Map(); // Old objects
this.permanentGeneration = new Map(); // Very old objects
this.gcCycles = 0;
this.promotionThreshold = 3; // How many GC cycles to survive to be promoted
}
allocateObject(id, data, size = 64) {
const obj = {
id: id,
data: data,
size: size,
generation: 'young',
gcSurvived: 0,
allocatedAt: Date.now(),
lastAccessed: Date.now()
};
this.youngGeneration.set(id, obj);
console.log(`Allocated ${id} in young generation`);
return obj;
}
accessObject(id) {
let obj = this.youngGeneration.get(id) ||
this.oldGeneration.get(id) ||
this.permanentGeneration.get(id);
if (obj) {
obj.lastAccessed = Date.now();
console.log(`Accessed object ${id}`);
}
return obj;
}
// Minor GC - young generation only
runMinorGC() {
console.log('Running Minor GC (young generation)...');
this.gcCycles++;
const survivors = [];
const toPromote = [];
this.youngGeneration.forEach((obj, id) => {
// Simulation: objects accessed in the last 5 seconds survive
const timeSinceLastAccess = Date.now() - obj.lastAccessed;
if (timeSinceLastAccess < 5000) {
obj.gcSurvived++;
survivors.push({ id, obj });
// Promotion to old generation
if (obj.gcSurvived >= this.promotionThreshold) {
toPromote.push({ id, obj });
}
console.log(`Object ${id} survived (count: ${obj.gcSurvived})`);
} else {
console.log(`Collected young object ${id}`);
}
});
// Clear young generation
this.youngGeneration.clear();
// Restore survivors
survivors.forEach(({ id, obj }) => {
if (!toPromote.find(p => p.id === id)) {
this.youngGeneration.set(id, obj);
}
});
// Promote to old generation
toPromote.forEach(({ id, obj }) => {
obj.generation = 'old';
this.oldGeneration.set(id, obj);
console.log(`Promoted ${id} to old generation`);
});
console.log(`Minor GC completed. Young: ${this.youngGeneration.size}, Old: ${this.oldGeneration.size}`);
}
// Major GC - all generations
runMajorGC() {
console.log('Running Major GC (all generations)...');
const collectFromGeneration = (generation, name) => {
const survivors = new Map();
let collected = 0;
generation.forEach((obj, id) => {
const timeSinceLastAccess = Date.now() - obj.lastAccessed;
// Old generation has a longer lifetime
const threshold = name === 'old' ? 10000 : 5000;
if (timeSinceLastAccess < threshold) {
survivors.set(id, obj);
} else {
collected++;
console.log(`Collected ${name} object ${id}`);
}
});
generation.clear();
survivors.forEach((obj, id) => generation.set(id, obj));
return collected;
};
const youngCollected = collectFromGeneration(this.youngGeneration, 'young');
const oldCollected = collectFromGeneration(this.oldGeneration, 'old');
console.log(`Major GC completed. Collected ${youngCollected + oldCollected} objects`);
console.log(`Remaining - Young: ${this.youngGeneration.size}, Old: ${this.oldGeneration.size}`);
}
// Automatic GC based on heuristics
autoGC() {
const youngSize = this.youngGeneration.size;
const oldSize = this.oldGeneration.size;
// GC triggers
if (youngSize > 100) { // Many young objects
this.runMinorGC();
}
if (oldSize > 50 || this.gcCycles % 10 === 0) { // Many old objects or every 10 cycles
this.runMajorGC();
}
}
getGenerationStats() {
return {
young: this.youngGeneration.size,
old: this.oldGeneration.size,
permanent: this.permanentGeneration.size,
totalGCCycles: this.gcCycles
};
}
}
// Generational GC demonstration
const genGC = new GenerationalGCDemo();
// Simulation of allocation patterns
function simulateAllocationPattern() {
// Creating many short-lived objects
for (let i = 0; i < 50; i++) {
genGC.allocateObject(`temp_${i}`, `Temporary object ${i}`);
}
// Creating a few long-lived objects
for (let i = 0; i < 5; i++) {
const longLived = genGC.allocateObject(`long_${i}`, `Long-lived object ${i}`);
// Simulating regular access
setInterval(() => {
genGC.accessObject(`long_${i}`);
}, 1000);
}
// Automatic GC every two seconds
setInterval(() => {
genGC.autoGC();
console.log('Generation stats:', genGC.getGenerationStats());
}, 2000);
}The simulation simplifies one thing: a real GC does not check when you last used an object, only whether it is reachable. V8 has a young and an old generation, and the permanent generation is a concept from old Java.
Types of Memory Leaks
Global variables, listeners, timers, closures and the DOM
A leak is an object that is still reachable even though you no longer need it. Here are five typical sources together with their correct versions:
// Problem: Uncontrolled global variables
class GlobalVariableLeaks {
static demonstrateLeaks() {
// BAD: Accidental global variables
// Note: code inside a class always runs in strict mode, so both lines below throw here.
// This leak happens in a plain script without 'use strict'.
function accidentalGlobal() {
// Missing 'var', 'let', 'const' - creates a global variable!
leakedVariable = 'This will leak!';
// Also global via 'this' in non-strict mode
this.anotherLeak = { data: new Array(1000).fill('leak') };
}
accidentalGlobal();
// These variables will remain in memory until the end of the application
console.log('Leaked variables:', window.leakedVariable, window.anotherLeak);
}
static demonstrateSolutions() {
// GOOD: Use strict mode
'use strict';
function properFunction() {
// ReferenceError instead of a global variable
// notDeclared = 'This will throw error in strict mode';
let properVariable = 'This is properly scoped';
const anotherProper = { data: 'safe' };
return { properVariable, anotherProper };
}
// GOOD: Module pattern
const safeModule = (function() {
let privateData = [];
return {
addData: function(item) {
privateData.push(item);
},
getData: function() {
return privateData.slice(); // Return copy
},
clear: function() {
privateData = [];
}
};
})();
return { safeModule };
}
}
// 2. Event Listeners
class EventListenerLeaks {
constructor() {
this.data = new Array(10000).fill('memory consuming data');
this.handlers = new Map();
}
// BAD: Event listeners without cleanup
addLeakyListeners() {
const button = document.getElementById('leaky-button');
// Problem: listener references an object that may hold a lot of data
const handler = () => {
console.log('Clicked!', this.data.length);
};
button?.addEventListener('click', handler);
// When the component is removed, the listener remains!
// The entire object cannot be collected by GC
}
// GOOD: Proper cleanup
addProperListeners() {
const button = document.getElementById('proper-button');
const handler = (event) => {
console.log('Proper click!', event.target.id);
};
this.handlers.set('button-click', handler);
button?.addEventListener('click', handler);
}
cleanup() {
// Always remove event listeners during cleanup
this.handlers.forEach((handler, key) => {
if (key === 'button-click') {
const button = document.getElementById('proper-button');
button?.removeEventListener('click', handler);
}
});
this.handlers.clear();
console.log('Event listeners cleaned up');
}
// Modern approach: AbortController
addModernListeners() {
const controller = new AbortController();
const signal = controller.signal;
document.addEventListener('click', (event) => {
console.log('Modern click!', event.target);
}, { signal });
// Cleanup all listeners at once
setTimeout(() => {
controller.abort();
console.log('All listeners aborted');
}, 10000);
}
}
// 3. Timers and Intervals
class TimerLeaks {
constructor() {
this.data = new Array(100000).fill('timer data');
this.timers = new Set();
}
// BAD: Timers without cleanup
createLeakyTimers() {
// Problem: setInterval references the entire class
const intervalId = setInterval(() => {
console.log('Leaky timer tick', this.data.length);
}, 1000);
// Timer is never cleared!
// Object cannot be collected by GC
return intervalId;
}
// GOOD: Tracked timers
createTrackedTimers() {
const intervalId = setInterval(() => {
console.log('Tracked timer tick');
}, 1000);
this.timers.add(intervalId);
// Auto cleanup after time
const timeoutId = setTimeout(() => {
this.clearTimer(intervalId);
}, 10000);
this.timers.add(timeoutId);
return intervalId;
}
clearTimer(timerId) {
clearInterval(timerId);
clearTimeout(timerId);
this.timers.delete(timerId);
console.log(`Timer ${timerId} cleared`);
}
cleanup() {
this.timers.forEach(timerId => {
clearInterval(timerId);
clearTimeout(timerId);
});
this.timers.clear();
console.log('All timers cleaned up');
}
// Modern approach: AbortController for async operations
createAbortableTimer() {
const controller = new AbortController();
const timer = {
start: () => {
const interval = setInterval(() => {
if (controller.signal.aborted) {
clearInterval(interval);
return;
}
console.log('Abortable timer tick');
}, 1000);
return interval;
},
stop: () => {
controller.abort();
}
};
return timer;
}
}
// 4. Closures
class ClosureLeaks {
static demonstrateLeaks() {
function createLeakyClosures() {
const largeData = new Array(1000000).fill('leak data');
// Problem: closure holds a reference to the entire scope
return {
// Even if we only use a small part of the data
getSmallPart: function() {
return largeData.slice(0, 10);
},
// This function also keeps the entire largeData in memory
getLength: function() {
return largeData.length;
}
};
}
const leaky = createLeakyClosures();
console.log('Small part:', leaky.getSmallPart());
// largeData remains in memory even though we only need the length!
return leaky;
}
static demonstrateSolutions() {
function createOptimizedClosures() {
const largeData = new Array(1000000).fill('optimized data');
// GOOD: Extract only the needed data
const smallPart = largeData.slice(0, 10);
const dataLength = largeData.length;
// largeData can be collected by GC
return {
getSmallPart: function() {
return smallPart;
},
getLength: function() {
return dataLength;
}
};
}
// GOOD: Null references when done
function createCleanClosures() {
let data = new Array(100000).fill('clean data');
const api = {
process: function() {
const result = data.map(item => item.toUpperCase());
data = null; // Explicit cleanup!
return result;
}
};
return api;
}
return { createOptimizedClosures, createCleanClosures };
}
}
// 5. DOM References
class DOMReferenceLeaks {
constructor() {
this.domReferences = new Map();
this.observers = [];
}
// BAD: Holding DOM references
createDOMLeaks() {
// Problem: references to removed DOM elements
const elements = document.querySelectorAll('.dynamic-content');
elements.forEach((element, index) => {
this.domReferences.set(`element_${index}`, {
node: element, // Direct reference!
data: new Array(1000).fill(`data_${index}`)
});
});
// Even if elements are removed from the DOM,
// they will remain in memory due to these references!
}
// GOOD: WeakMap for DOM references
createSafeDOMReferences() {
const elementData = new WeakMap();
const elements = document.querySelectorAll('.safe-content');
elements.forEach((element, index) => {
// WeakMap allows GC of element when it is removed from DOM
elementData.set(element, {
id: index,
data: new Array(1000).fill(`safe_data_${index}`)
});
});
return elementData;
}
// Proper cleanup for DOM observers
setupDOMObserver() {
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
console.log('DOM changed:', mutation.type);
});
});
observer.observe(document.body, {
childList: true,
subtree: true
});
this.observers.push(observer);
// Auto cleanup
setTimeout(() => {
this.cleanupObservers();
}, 30000);
}
cleanupObservers() {
this.observers.forEach(observer => {
observer.disconnect();
});
this.observers = [];
console.log('DOM observers cleaned up');
}
cleanup() {
this.domReferences.clear();
this.cleanupObservers();
}
}The most common cause is forgotten event listeners and timers. A listener on an object that lives longer than the component, for example on document, keeps alive everything its closure reaches. AbortController removes many listeners with a single abort(), and a WeakMap does not prevent a DOM element from being collected. In the global variables example, remember that classes run in strict mode, so assigning to an undeclared variable throws a ReferenceError.
Memory Leak Detection and Monitoring
Performance API for Memory Monitoring
A leak gives itself away through steadily growing memory usage. Every few seconds the monitor records the heap size and warns when it keeps growing:
// Memory monitoring utilities
class MemoryMonitor {
constructor() {
this.measurements = [];
this.isMonitoring = false;
this.alertThreshold = 50 * 1024 * 1024; // 50MB
}
startMonitoring(interval = 5000) {
if (this.isMonitoring) return;
this.isMonitoring = true;
console.log('Started memory monitoring');
const monitor = () => {
if (!this.isMonitoring) return;
const memInfo = this.getMemoryInfo();
this.measurements.push({
...memInfo,
timestamp: Date.now()
});
this.checkMemoryAlerts(memInfo);
this.trimMeasurements();
setTimeout(monitor, interval);
};
monitor();
}
stopMonitoring() {
this.isMonitoring = false;
console.log('Stopped memory monitoring');
}
getMemoryInfo() {
if (performance.memory) {
return {
usedJSHeapSize: performance.memory.usedJSHeapSize,
totalJSHeapSize: performance.memory.totalJSHeapSize,
jsHeapSizeLimit: performance.memory.jsHeapSizeLimit,
usedPercent: (performance.memory.usedJSHeapSize / performance.memory.jsHeapSizeLimit) * 100
};
}
return {
usedJSHeapSize: 0,
totalJSHeapSize: 0,
jsHeapSizeLimit: 0,
usedPercent: 0
};
}
checkMemoryAlerts(memInfo) {
if (memInfo.usedJSHeapSize > this.alertThreshold) {
console.warn('High memory usage detected:', {
used: this.formatBytes(memInfo.usedJSHeapSize),
percent: memInfo.usedPercent.toFixed(2) + '%'
});
this.triggerMemoryCleanup();
}
// Check for memory leaks (constant growth)
if (this.measurements.length > 10) {
const recent = this.measurements.slice(-10);
const growth = recent[recent.length - 1].usedJSHeapSize - recent[0].usedJSHeapSize;
const timeSpan = recent[recent.length - 1].timestamp - recent[0].timestamp;
const growthRate = growth / timeSpan; // bytes per ms
if (growthRate > 1000) { // > 1KB/s growth
console.warn('Potential memory leak detected:', {
growthRate: this.formatBytes(growthRate * 1000) + '/s',
totalGrowth: this.formatBytes(growth)
});
}
}
}
triggerMemoryCleanup() {
// Force garbage collection if available (dev tools)
if (window.gc) {
window.gc();
console.log('Forced garbage collection');
}
// Cleanup event
window.dispatchEvent(new CustomEvent('memoryCleanup', {
detail: { memoryUsage: this.getMemoryInfo() }
}));
}
generateMemoryReport() {
if (this.measurements.length === 0) {
return { error: 'No measurements available' };
}
const latest = this.measurements[this.measurements.length - 1];
const oldest = this.measurements[0];
return {
currentUsage: {
used: this.formatBytes(latest.usedJSHeapSize),
total: this.formatBytes(latest.totalJSHeapSize),
limit: this.formatBytes(latest.jsHeapSizeLimit),
percent: latest.usedPercent.toFixed(2) + '%'
},
trend: {
totalGrowth: this.formatBytes(latest.usedJSHeapSize - oldest.usedJSHeapSize),
timeSpan: this.formatTime(latest.timestamp - oldest.timestamp),
measurementCount: this.measurements.length
},
recommendations: this.generateRecommendations()
};
}
generateRecommendations() {
const recommendations = [];
const latest = this.measurements[this.measurements.length - 1];
if (latest.usedPercent > 80) {
recommendations.push('Memory usage is very high - consider implementing cleanup strategies');
}
if (this.measurements.length > 5) {
const recentGrowth = this.measurements.slice(-5);
const avgGrowth = recentGrowth.reduce((sum, m, i) =>
i === 0 ? 0 : sum + (m.usedJSHeapSize - recentGrowth[i-1].usedJSHeapSize), 0
) / (recentGrowth.length - 1);
if (avgGrowth > 1024 * 1024) { // > 1MB average growth
recommendations.push('Consistent memory growth detected - check for memory leaks');
}
}
return recommendations;
}
formatBytes(bytes) {
const units = ['B', 'KB', 'MB', 'GB'];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size.toFixed(2)} ${units[unitIndex]}`;
}
formatTime(ms) {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) return `${hours}h ${minutes % 60}m`;
if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
return `${seconds}s`;
}
trimMeasurements() {
// Keep only last 100 measurements
if (this.measurements.length > 100) {
this.measurements = this.measurements.slice(-100);
}
}
}
// Memory leak detector
class MemoryLeakDetector {
constructor() {
this.snapshots = [];
this.leakPatterns = new Map();
}
takeSnapshot(label = 'snapshot') {
const snapshot = {
label: label,
timestamp: Date.now(),
memory: performance.memory ? {
used: performance.memory.usedJSHeapSize,
total: performance.memory.totalJSHeapSize
} : null,
objectCounts: this.countObjects()
};
this.snapshots.push(snapshot);
console.log(`Memory snapshot taken: ${label}`);
return snapshot;
}
countObjects() {
// Approximate object counting (in reality use dev tools)
const counts = {
arrays: 0,
objects: 0,
functions: 0,
strings: 0
};
// Simulation - in real implementation use heap snapshot API
return counts;
}
compareSnapshots(snapshot1Label, snapshot2Label) {
const snap1 = this.snapshots.find(s => s.label === snapshot1Label);
const snap2 = this.snapshots.find(s => s.label === snapshot2Label);
if (!snap1 || !snap2) {
console.error('Snapshots not found');
return null;
}
const comparison = {
memoryGrowth: snap2.memory ? snap2.memory.used - snap1.memory.used : 0,
timeSpan: snap2.timestamp - snap1.timestamp,
objectGrowth: {},
suspiciousGrowth: []
};
// Object growth analysis
Object.keys(snap1.objectCounts).forEach(type => {
const growth = snap2.objectCounts[type] - snap1.objectCounts[type];
comparison.objectGrowth[type] = growth;
if (growth > 100) { // Suspicious growth threshold
comparison.suspiciousGrowth.push({
type: type,
growth: growth,
growthRate: growth / (comparison.timeSpan / 1000) // per second
});
}
});
return comparison;
}
detectLeakPatterns() {
if (this.snapshots.length < 3) return [];
const patterns = [];
const recent = this.snapshots.slice(-3);
// Check for consistent memory growth
const memoryGrowth = recent.map((snap, i) =>
i === 0 ? 0 : snap.memory.used - recent[i-1].memory.used
).slice(1);
const consistentGrowth = memoryGrowth.every(growth => growth > 0);
if (consistentGrowth) {
const avgGrowth = memoryGrowth.reduce((a, b) => a + b) / memoryGrowth.length;
patterns.push({
type: 'consistent_memory_growth',
severity: avgGrowth > 1024 * 1024 ? 'high' : 'medium',
description: `Memory consistently growing by ${(avgGrowth / 1024 / 1024).toFixed(2)}MB per measurement`,
avgGrowth: avgGrowth
});
}
return patterns;
}
}
// Global memory monitor instance
const memoryMonitor = new MemoryMonitor();
const leakDetector = new MemoryLeakDetector();
// Usage example
function startMemoryAnalysis() {
memoryMonitor.startMonitoring(2000); // Every 2 seconds
// Take initial snapshot
leakDetector.takeSnapshot('initial');
// Simulate some operations and take snapshots
setTimeout(() => {
// Simulate memory allocation
const data = new Array(100000).fill('test data');
leakDetector.takeSnapshot('after_allocation');
}, 5000);
setTimeout(() => {
// Generate memory report
const report = memoryMonitor.generateMemoryReport();
console.log('Memory Report:', report);
const patterns = leakDetector.detectLeakPatterns();
console.log('Leak Patterns:', patterns);
}, 10000);
}performance.memory works only in Chromium and reports approximate values, and window.gc exists only when the browser is started with the --js-flags=--expose-gc flag. DevTools gives you a more reliable diagnosis: open the Memory panel, take a heap snapshot, repeat the suspicious action, take a second snapshot, compare them and find the retained objects.
Best Practices for Memory Management
Proactive Memory Management
Prevention beats cure. A component with a memory budget cleans up unused resources, object pooling reuses objects, and WeakRef lets you keep a cache without blocking the GC:
// Memory-aware component design
class MemoryAwareComponent {
constructor(config) {
this.config = config;
this.resources = new Map();
this.cleanup = new Set();
this.memoryBudget = config.memoryBudget || 10 * 1024 * 1024; // 10MB default
}
// Resource tracking
allocateResource(key, factory, size = 0) {
if (this.getCurrentMemoryUsage() + size > this.memoryBudget) {
this.performCleanup();
}
const resource = factory();
this.resources.set(key, {
data: resource,
size: size,
allocatedAt: Date.now(),
lastAccessed: Date.now()
});
return resource;
}
getResource(key) {
const resource = this.resources.get(key);
if (resource) {
resource.lastAccessed = Date.now();
return resource.data;
}
return null;
}
getCurrentMemoryUsage() {
return Array.from(this.resources.values())
.reduce((total, resource) => total + resource.size, 0);
}
performCleanup() {
console.log('Performing memory cleanup...');
const now = Date.now();
const staleThreshold = 5 * 60 * 1000; // 5 minutes
// Remove stale resources
for (const [key, resource] of this.resources) {
if (now - resource.lastAccessed > staleThreshold) {
this.deallocateResource(key);
}
}
// Run custom cleanup functions
this.cleanup.forEach(cleanupFn => {
try {
cleanupFn();
} catch (error) {
console.error('Cleanup function failed:', error);
}
});
}
deallocateResource(key) {
const resource = this.resources.get(key);
if (resource) {
// Custom cleanup if resource has cleanup method
if (resource.data && typeof resource.data.cleanup === 'function') {
resource.data.cleanup();
}
this.resources.delete(key);
console.log(`Deallocated resource: ${key}`);
}
}
addCleanupFunction(fn) {
this.cleanup.add(fn);
}
removeCleanupFunction(fn) {
this.cleanup.delete(fn);
}
destroy() {
// Cleanup all resources
this.resources.forEach((_, key) => {
this.deallocateResource(key);
});
// Run all cleanup functions
this.cleanup.forEach(cleanupFn => {
try {
cleanupFn();
} catch (error) {
console.error('Cleanup function failed during destroy:', error);
}
});
this.cleanup.clear();
console.log('Component destroyed and cleaned up');
}
}
// Object pooling for frequently used objects
class ObjectPool {
constructor(factory, resetFn, initialSize = 10) {
this.factory = factory;
this.resetFn = resetFn;
this.pool = [];
this.activeObjects = new Set();
// Pre-allocate objects
for (let i = 0; i < initialSize; i++) {
this.pool.push(this.factory());
}
}
acquire() {
let obj;
if (this.pool.length > 0) {
obj = this.pool.pop();
} else {
obj = this.factory();
console.log('Created new object (pool exhausted)');
}
this.activeObjects.add(obj);
return obj;
}
release(obj) {
if (this.activeObjects.has(obj)) {
this.activeObjects.delete(obj);
// Reset object to initial state
if (this.resetFn) {
this.resetFn(obj);
}
this.pool.push(obj);
}
}
getStats() {
return {
poolSize: this.pool.length,
activeObjects: this.activeObjects.size,
totalObjects: this.pool.length + this.activeObjects.size
};
}
}
// Object pooling usage example
const vectorPool = new ObjectPool(
() => ({ x: 0, y: 0, z: 0 }), // factory
(vector) => { vector.x = 0; vector.y = 0; vector.z = 0; }, // reset
50 // initial size
);
function performVectorCalculations() {
const vectors = [];
// Acquire vectors from pool instead of creating new ones
for (let i = 0; i < 100; i++) {
const vector = vectorPool.acquire();
vector.x = Math.random();
vector.y = Math.random();
vector.z = Math.random();
vectors.push(vector);
}
// Do calculations...
// Release vectors back to pool
vectors.forEach(vector => vectorPool.release(vector));
console.log('Vector pool stats:', vectorPool.getStats());
}
// WeakRef for optional caching
class WeakRefCache {
constructor() {
this.cache = new Map();
this.finalizationRegistry = new FinalizationRegistry((key) => {
console.log(`Object with key '${key}' was garbage collected`);
this.cache.delete(key);
});
}
set(key, value) {
const weakRef = new WeakRef(value);
this.cache.set(key, weakRef);
this.finalizationRegistry.register(value, key);
}
get(key) {
const weakRef = this.cache.get(key);
if (!weakRef) return null;
const value = weakRef.deref();
if (value === undefined) {
// Object was garbage collected
this.cache.delete(key);
return null;
}
return value;
}
has(key) {
return this.get(key) !== null;
}
delete(key) {
this.cache.delete(key);
}
size() {
// Clean up dead references
for (const [key, weakRef] of this.cache) {
if (weakRef.deref() === undefined) {
this.cache.delete(key);
}
}
return this.cache.size;
}
}WeakRef creates a weak reference that does not block garbage collection: deref() returns the object, or undefined once the GC has taken it. A FinalizationRegistry callback might never be called, so treat it as supplementary cleanup, not application logic.
Memory Profiling Tools
Finally, a profiler that measures memory usage around a chosen method and attaches itself to it through a decorator:
// Development memory profiling utilities
class MemoryProfiler {
constructor() {
this.profiles = new Map();
this.isProfilingEnabled = process.env.NODE_ENV === 'development';
}
startProfile(name) {
if (!this.isProfilingEnabled) return;
const profile = {
name: name,
startTime: performance.now(),
startMemory: performance.memory ? {
used: performance.memory.usedJSHeapSize,
total: performance.memory.totalJSHeapSize
} : null,
snapshots: []
};
this.profiles.set(name, profile);
console.log(`Started memory profile: ${name}`);
}
snapshot(profileName, label) {
if (!this.isProfilingEnabled) return;
const profile = this.profiles.get(profileName);
if (!profile) return;
const snapshot = {
label: label,
timestamp: performance.now(),
memory: performance.memory ? {
used: performance.memory.usedJSHeapSize,
total: performance.memory.totalJSHeapSize
} : null
};
profile.snapshots.push(snapshot);
console.log(`Memory snapshot: ${profileName}.${label}`);
}
endProfile(name) {
if (!this.isProfilingEnabled) return;
const profile = this.profiles.get(name);
if (!profile) return;
profile.endTime = performance.now();
profile.endMemory = performance.memory ? {
used: performance.memory.usedJSHeapSize,
total: performance.memory.totalJSHeapSize
} : null;
const report = this.generateProfileReport(profile);
console.log(`Memory profile completed: ${name}`, report);
return report;
}
generateProfileReport(profile) {
const duration = profile.endTime - profile.startTime;
let memoryGrowth = 0;
if (profile.startMemory && profile.endMemory) {
memoryGrowth = profile.endMemory.used - profile.startMemory.used;
}
const snapshots = profile.snapshots.map((snapshot, index) => {
const prevSnapshot = index > 0 ? profile.snapshots[index - 1] :
{ memory: profile.startMemory, timestamp: profile.startTime };
return {
label: snapshot.label,
timeDelta: snapshot.timestamp - prevSnapshot.timestamp,
memoryDelta: snapshot.memory && prevSnapshot.memory ?
snapshot.memory.used - prevSnapshot.memory.used : 0
};
});
return {
duration: duration.toFixed(2) + 'ms',
memoryGrowth: memoryGrowth,
memoryGrowthFormatted: this.formatBytes(memoryGrowth),
snapshots: snapshots,
recommendations: this.generateProfileRecommendations(profile, memoryGrowth)
};
}
generateProfileRecommendations(profile, memoryGrowth) {
const recommendations = [];
if (memoryGrowth > 1024 * 1024) { // > 1MB growth
recommendations.push('Significant memory growth detected - review object allocations');
}
if (profile.snapshots.length > 0) {
const biggestGrowth = Math.max(...profile.snapshots.map((s, i) => {
const prev = i > 0 ? profile.snapshots[i-1] : { memory: profile.startMemory };
return s.memory && prev.memory ? s.memory.used - prev.memory.used : 0;
}));
if (biggestGrowth > 512 * 1024) { // > 512KB single growth
recommendations.push('Large single allocation detected - consider chunking or streaming');
}
}
return recommendations;
}
formatBytes(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(Math.abs(bytes)) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
}
// Global profiler instance
const memoryProfiler = new MemoryProfiler();
// Decorator for automatic function profiling
function profileMemory(name) {
return function(target, propertyKey, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args) {
const profileName = name || `${target.constructor.name}.${propertyKey}`;
memoryProfiler.startProfile(profileName);
try {
const result = originalMethod.apply(this, args);
if (result instanceof Promise) {
return result.finally(() => {
memoryProfiler.endProfile(profileName);
});
} else {
memoryProfiler.endProfile(profileName);
return result;
}
} catch (error) {
memoryProfiler.endProfile(profileName);
throw error;
}
};
return descriptor;
};
}
// Usage example
class DataProcessor {
@profileMemory('processLargeDataset')
processLargeDataset(data) {
memoryProfiler.snapshot('processLargeDataset', 'start');
// Process data in chunks
const chunks = this.chunkArray(data, 1000);
const results = [];
chunks.forEach((chunk, index) => {
memoryProfiler.snapshot('processLargeDataset', `chunk_${index}`);
const processed = chunk.map(item => this.transformItem(item));
results.push(...processed);
});
memoryProfiler.snapshot('processLargeDataset', 'end');
return results;
}
chunkArray(array, size) {
const chunks = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
transformItem(item) {
return { ...item, processed: true, timestamp: Date.now() };
}
}@profileMemory is a TypeScript-style decorator that needs the experimentalDecorators option. In plain JavaScript, decorators are still a Stage 3 proposal, so this code requires a compiler.
Summary
Memory management in JavaScript requires:
- Understanding Garbage Collection - how it works and when it runs
- Awareness of Memory Leaks - main causes and how to avoid them
- A proactive approach - monitoring and cleanup
- The right patterns - object pooling, WeakMap, AbortController
- Diagnostic tools - profiling and monitoring
Key principles: clean up your listeners, timers and observers, use WeakMap and WeakSet for optional references, monitor memory in production, use object pooling for frequently allocated objects, avoid accidental global variables and test your application for leaks. My advice: write every addEventListener, setInterval and observe together with the code that removes it. In the editor below you will test garbage collection on examples, and in the next lesson we return to TypeScript and .d.ts files.
Remember: the garbage collector only cleans up what no path leads to anymore, so you have to cut the paths to unneeded data yourself.
Code for this lesson: index.js
// Garbage Collection and Memory Leaks in JavaScript
console.log("DNA Memory Management Laboratory");
console.log("Analysis of garbage collection and memory leaks\n");
// ====================================
// 1. HOW MEMORY WORKS IN JAVASCRIPT
// ====================================
console.log("=== 1. Data storage types ===\n");
// Stack (primitive values)
let dinosaurCount = 5;
let parkName = "Jurassic Park";
let isActive = true;
console.log("Stack memory (primitive values):");
console.log("- dinosaurCount:", dinosaurCount);
console.log("- parkName:", parkName);
console.log("- isActive:", isActive);
// Heap (objects and references)
let dinosaur1 = { name: "T-Rex", age: 68000000 };
let dinosaur2 = dinosaur1; // Same reference!
console.log("\nHeap memory (objects):");
console.log("dinosaur1:", dinosaur1);
console.log("dinosaur2:", dinosaur2);
console.log("dinosaur1 === dinosaur2:", dinosaur1 === dinosaur2);
// ====================================
// 2. GARBAGE COLLECTION
// ====================================
console.log("\n=== 2. Garbage Collection ===\n");
// Mark and Sweep Algorithm
function demonstrateGC() {
let tempDinosaur = { name: "Velociraptor", age: 75000000 };
console.log("Created a temporary dinosaur:", tempDinosaur.name);
// After leaving the function, tempDinosaur is marked for removal
// The Garbage Collector automatically frees the memory
}
demonstrateGC();
console.log("Function completed - memory will be freed by the GC");
// References and GC
let dino = { name: "Triceratops" };
let dinoRef1 = dino;
let dinoRef2 = dino;
console.log("\nNumber of references to the object: 3");
dino = null;
console.log("After removing 'dino': 2 references remain");
dinoRef1 = null;
console.log("After removing 'dinoRef1': 1 reference remains");
dinoRef2 = null;
console.log("After removing 'dinoRef2': 0 references - the object will be removed by the GC!");
// ====================================
// 3. MEMORY LEAKS - COMMON CAUSES
// ====================================
console.log("\n=== 3. Memory Leaks - Common mistakes ===\n");
// LEAK 1: Global variables
console.log("LEAK 1: Unintended global variables");
function createAccidentalGlobal() {
// No 'let', 'const', or 'var' - creates a global variable!
// accidentalDinosaur = { name: "Leaked Dino" }; // DON'T DO THIS!
console.log("Always use let/const/var!");
}
// LEAK 2: Forgotten timers
console.log("\nLEAK 2: Forgotten timers/intervals");
let leakyTimer;
function demonstrateTimerLeak() {
const hugeData = new Array(1000000).fill("DNA sequence");
leakyTimer = setInterval(() => {
// hugeData is captured in the closure and will never be freed!
console.log("Timer is running with access to hugeData");
}, 1000);
// Solution: Always clear timers
// clearInterval(leakyTimer);
}
console.log("Timer created - memory grows!");
console.log("Solution: clearInterval(leakyTimer);");
// LEAK 3: DOM references
console.log("\nLEAK 3: Storing DOM references");
const domReferences = [];
function demonstrateDOMLeaks() {
// Simulating a DOM element
const element = { id: "dino-card-1", data: "Massive data..." };
domReferences.push(element);
// Even if the element is removed from the DOM,
// the reference in the array still holds it in memory!
console.log("Element added to the references array");
}
// LEAK 4: Closures
console.log("\nLEAK 4: Overuse of closures");
function createLeakyClosure() {
const hugeArray = new Array(1000000).fill({ dino: "data" });
return function() {
// The closure holds a reference to the entire hugeArray
console.log("Array size:", hugeArray.length);
};
}
const leakyFunction = createLeakyClosure();
console.log("Closure created - hugeArray remains in memory");
// ====================================
// 4. HOW TO AVOID MEMORY LEAKS
// ====================================
console.log("\n=== 4. Best practices ===\n");
// 1. Clear timers
function properTimerUsage() {
const timer = setInterval(() => {
console.log("Timer is running");
}, 1000);
// Cleanup
setTimeout(() => {
clearInterval(timer);
console.log("Timer has been cleared");
}, 3000);
}
// 2. Use WeakMap/WeakSet
console.log("Use WeakMap for metadata:");
const metadataMap = new WeakMap();
let dinosaurObject = { name: "Stegosaurus" };
metadataMap.set(dinosaurObject, { discovered: 1877, location: "Colorado" });
console.log("Metadata added to WeakMap");
dinosaurObject = null; // The object can be removed by the GC!
console.log("Object removed - the metadata will also be removed");
// 3. Proper event listeners cleanup
class DinosaurMonitor {
constructor() {
this.dinosaurs = [];
this.eventHandler = this.onUpdate.bind(this);
}
onUpdate(data) {
this.dinosaurs.push(data);
}
start() {
// addEventListener('update', this.eventHandler);
console.log("Monitor started with bind()");
}
stop() {
// removeEventListener('update', this.eventHandler);
console.log("Monitor stopped - event listener removed");
}
}
// 4. Nullify references
console.log("\nNullify large objects when they are no longer needed:");
let bigDinosaurData = new Array(100000).fill({ genome: "ATCG..." });
console.log("Large object created");
// When you finish working with the data:
bigDinosaurData = null;
console.log("Object nullified - ready for GC");
// ====================================
// 5. MEMORY MONITORING
// ====================================
console.log("\n=== 5. Memory monitoring ===\n");
if (performance.memory) {
console.log("Memory information:");
console.log("- Used JS Heap:", performance.memory.usedJSHeapSize);
console.log("- Total JS Heap:", performance.memory.totalJSHeapSize);
console.log("- Limit:", performance.memory.jsHeapSizeLimit);
} else {
console.log("performance.memory unavailable (use Chrome DevTools)");
}
console.log("\nDebugging tools:");
console.log("1. Chrome DevTools β Memory β Heap Snapshot");
console.log("2. Performance profiler");
console.log("3. Memory timeline");
console.log("\nRemember:");
console.log("- Always clear timers and event listeners");
console.log("- Use WeakMap/WeakSet when possible");
console.log("- Nullify large objects after use");
console.log("- Avoid global variables");
console.log("- Monitor memory usage in DevTools");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the most common cause of memory leaks in JavaScript?
2. Which mechanism is the main Garbage Collection strategy in modern JavaScript?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Find and fix the memory leak in the provided code.
- Code editor
Remove unneeded references (global collections, closures) and event listeners that were never removed.
- Vertical ordering
Arrange the phases of the garbage collection process in the correct order:
- Vertical ordering
Arrange the stages of identifying a memory leak in an application in the correct order: