Memory Management in JavaScript
Learn how JavaScript manages memory, prevents leaks, and optimizes performance through automatic garbage collection and memory allocation strategies.
🧠 JavaScript Memory Model
JavaScript uses automatic memory management through garbage collection. Memory is allocated when objects are created and freed when they're no longer needed.
- Stack Memory - Fixed size, stores primitive values and references
- Heap Memory - Dynamic size, stores objects and complex data
- Garbage Collector - Automatically frees unused memory
💡 Memory Lifecycle
- Allocate - Memory assigned to objects
- Use - Read/write operations
- Release - Garbage collector frees memory
Key Concepts:
- Primitive values: Stack allocation
- Reference values: Heap allocation
- Automatic garbage collection
- Memory leaks can still occur
⚙️ Memory Allocation: Heap vs Stack
Stack Memory
Characteristics:
- Fixed size allocation
- Fast access (LIFO)
- Stores primitive values
- Stores function calls
- Automatic cleanup
Stored in Stack:
let x = 10;
const y = "hello";
var z = true;Heap Memory
Characteristics:
- Dynamic allocation
- Slower access
- Stores objects/arrays
- References stored in stack
- Garbage collected
Stored in Heap:
let obj = {};
let arr = [];
function Foo() {}🔄 Heap vs Stack in Action
See how different data types are stored in memory:
Memory Visualization:
STACK MEMORY HEAP MEMORY
┌─────────────────┐ ┌─────────────────┐
│ stackNumber: 42 │ │ │
│ stackString: "Hello" │ │ [1,2,3,4] │
│ heapArray: → ref1 │───────→│ {name:"John", │
│ heapObject: → ref2 │───┐ │ age:30, │
└─────────────────┘ │ │ city:"New York"}│
│ └─────────────────┘
└──→┌─────────────────┐
│ [4,5,6] │
└─────────────────┘🗑️ Garbage Collection
JavaScript's garbage collector automatically frees memory that is no longer reachable:
🗑️ Mark and Sweep Algorithm:
- Start from root objects (global)
- Mark all reachable objects
- Sweep unmarked objects
- Compact memory (optional)
⚡ Generational Collection:
Objects divided into generations (young/old)
Young generation collected frequently
Surviving objects promoted to old generation
Old generation collected less frequently
⚠️ Common Memory Leaks
These patterns can cause memory leaks in JavaScript applications:
Memory Leak Prevention:
| Leak Type | Cause | Solution |
|---|---|---|
| Global Variables | Missing var/let/const | Always declare variables |
| Timers/Intervals | Not cleared | Always clear when done |
| DOM References | Holding DOM elements | Use WeakMap/WeakSet |
| Closures | Holding large data | Release references |
🚀 Memory Optimization
Techniques to optimize memory usage in JavaScript applications:
💡 Optimization Strategies:
Reuse objects instead of creating new ones
Weak References:Use WeakMap/WeakSet for temporary references
Process large data in chunks
Lazy Loading:Load resources only when needed
📊 Monitoring & Debugging
Tools and techniques for monitoring memory usage:
Browser DevTools Memory Tools:
Chrome DevTools:
- Performance tab
- Memory tab
- Heap snapshots
- Allocation timeline
Firefox DevTools:
- Memory tool
- Allocations
- Census view
- Dominators view
Safari Web Inspector:
- Timelines
- JavaScript allocations
- Memory timeline
🎯 Best Practices for Memory Management
✅ Do:
- Use const/let instead of var
- Clear intervals/timeouts
- Remove event listeners
- Use WeakMap for DOM references
- Process large data in chunks
- Use object pooling for frequent allocations
❌ Don't:
- Create accidental global variables
- Keep unnecessary DOM references
- Forget to cleanup event listeners
- Use closures for large data unnecessarily
- Process entire large datasets at once
- Ignore memory profiling results