Performance: Heap snapshot for memory leaks
Heap snapshots help identify memory leaks that cause increased memory usage and slow down Node.js applications over time.
Jump into concepts and practice - no test required
/* 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 |
getHeapSnapshot() method to create heap snapshots?v8 module provides access to V8 engine features including heap snapshots.getHeapSnapshot() method is part of the v8 module, not fs, http, or os.import { writeFileSync } from 'fs';
import { getHeapSnapshot } from 'v8';
const snapshotStream = getHeapSnapshot();
const chunks = [];
snapshotStream.on('data', chunk => chunks.push(chunk));
snapshotStream.on('end', () => {
writeFileSync('heap.heapsnapshot', Buffer.concat(chunks));
console.log('Snapshot saved');
});
What will this code do when run?getHeapSnapshot() returns a readable stream of the heap snapshot data.import { writeFileSync } from 'fs';
import { getHeapSnapshot } from 'v8';
const snapshotStream = getHeapSnapshot();
snapshotStream.on('data', chunk => {
writeFileSync('heap.heapsnapshot', chunk);
});
console.log('Snapshot saved');
What is the main problem?writeFileSync inside 'data' overwrites the file each time a chunk arrives.