Performance: Heap snapshot for memory leaks
HIGH IMPACT
Heap snapshots help identify memory leaks that cause increased memory usage and slow down Node.js applications over time.
/* Using heap snapshots to detect leaks */ const v8 = require('v8'); const fs = require('fs'); function takeHeapSnapshot(filename) { const snapshotStream = v8.getHeapSnapshot(); const fileStream = fs.createWriteStream(filename); snapshotStream.pipe(fileStream); } // Call takeHeapSnapshot periodically or on demand to analyze memory
/* No heap snapshot usage, memory leaks go unnoticed */ const http = require('http'); let cache = {}; http.createServer((req, res) => { // Storing data indefinitely without cleanup cache[Date.now()] = new Array(1000000).fill('*'); res.end('Hello World'); }).listen(3000);
| Pattern | Memory Usage | Garbage Collection | Snapshot Overhead | Verdict |
|---|---|---|---|---|
| No heap snapshot, leaks undetected | Unbounded growth | High GC pauses, frequent full GCs | None | [X] Bad |
| Regular heap snapshots and analysis | Controlled memory growth | Reduced GC pauses | Small CPU and I/O overhead during snapshot | [OK] Good |