Memory Management
Memory Management
Section titled “Memory Management”Introduction
Section titled “Introduction”Memory management in OOP refers to how objects are allocated, accessed, and freed in memory. Understanding this helps developers write efficient code and avoid memory leaks.
Stack vs Heap
Section titled “Stack vs Heap”| Aspect | Stack | Heap |
|---|---|---|
| What lives here | Primitive values, references | Objects |
| Allocation | Automatic | Manual (new) |
| Deallocation | When scope exits | Garbage collector |
| Speed | Fast | Slower |
| Size | Small (MB) | Large (GB) |
References
Section titled “References”Variables don’t contain objects — they contain references to objects.
let a = { value: 10 };let b = a; // b REFERS to the same object as a
b.value = 20;console.log(a.value); // 20 — a and b reference same object
a = { value: 30 };console.log(b.value); // 20 — b still points to originalGarbage Collection
Section titled “Garbage Collection”Garbage Collection (GC) is the automatic process of reclaiming memory occupied by objects that are no longer reachable.
Mark and Sweep Algorithm
Section titled “Mark and Sweep Algorithm”- Mark — GC starts from roots (global variables, stack references) and marks all reachable objects
- Sweep — Unmarked (unreachable) objects are freed
Common Memory Leaks
Section titled “Common Memory Leaks”// 1. Forgotten timerssetInterval(() => { /* holds references */ }, 1000);
// 2. Event listeners not removedelement.addEventListener("click", () => { /* holds reference */ });
// 3. Closures holding large datafunction createLeak() { const largeData = new Array(1000000); return () => console.log(largeData.length);}Best Practices
Section titled “Best Practices”- Nullify references when done with large objects
- Remove event listeners when components are destroyed
- Clear timers/intervals (
clearInterval,clearTimeout) - Use weak references for caches (
WeakMap,WeakSet)
Previous Topic: Object Lifecycle → Next Topic: Design Principles →