javascript / expert
Snippet
Fine-grained Garbage Collection Monitoring
Using PerformanceObserver with the 'gc' entry type allows applications to monitor memory management behavior in real-time. This is crucial for detecting memory pressure or 'stop-the-world' pauses that could impact latency in high-performance servers.
snippet.js
1
2
3
4
5
6
7
8
9
import { PerformanceObserver } from 'node:perf_hooks';const obs = new PerformanceObserver((list) => {const entry = list.getEntries()[0];console.log(`GC detected: ${entry.kind} | Duration: ${entry.duration}ms`);console.log(`Heap used: ${entry.detail.afterUsedHeapSize}`);});obs.observe({ entryTypes: ['gc'] });
nodejs
Breakdown
1
import { PerformanceObserver } from 'node:perf_hooks';
Accesses Node's performance measurement utility.
2
const entry = list.getEntries()[0];
Retrieves the specific GC performance entry containing duration and type.
3
entry.kind
Indicates the type of GC (e.g., 'scavenge' for minor or 'mark-sweep-compact' for major).
4
obs.observe({ entryTypes: ['gc'] });
Starts listening specifically for Garbage Collection events from the V8 engine.