Working with V8 Module

1. Getting Heap Statistics (v8.getHeapStatistics)

FieldMeaning
total_heap_sizeHeap allocated
used_heap_sizeCurrently in use
heap_size_limitMaximum allowed
malloced_memoryNative allocations
peak_malloced_memoryPeak native allocs

2. Getting Heap Space Statistics

SpaceHolds
new_spaceYoung generation (short-lived)
old_spaceLong-lived objects
code_spaceJIT code
map_spaceHidden classes
large_object_spaceBig allocations

3. Creating Heap Snapshots (v8.writeHeapSnapshot)

Example

import v8 from "node:v8";
const file = v8.writeHeapSnapshot();
// Open in Chrome DevTools → Memory → Load

4. Using Serialization

APIUse
v8.serialize(obj)Structured-clone Buffer
v8.deserialize(buf)Reverse
SupportsMaps, Sets, Dates, TypedArrays, BigInt

5. Using Cached Data

APIUse
vm.Script.cachedDataPre-compile JS for faster startup
--use-snapshot / node:seaSingle-executable apps

6. Setting Heap Limit (--max-old-space-size)

FlagDefault
--max-old-space-size=40964 GB old space
--max-semi-space-size=128Young space size
NODE_OPTIONSPass via env var

7. Profiling Memory Usage

ToolUse
Heap snapshotsCompare 3 snapshots to find leaks
--heap-profSampling profile output
v8.getHeapCodeStatisticsJIT code memory

8. Understanding Garbage Collection

PhaseDescription
Scavenge (Minor)Young space, fast and frequent
Mark-Sweep-Compact (Major)Full heap, slower
Incremental markingSplits work to reduce pauses
Concurrent markingRuns alongside JS
--expose-gcManually call global.gc() (debug only)

9. Using Weak References

APIUse
WeakRef(obj)Allow GC of target
WeakMap / WeakSetKeys can be GC'd
FinalizationRegistryCleanup callback after GC

10. Monitoring Memory Leaks

Leak Hunt Workflow

  1. Take heap snapshot (baseline)
  2. Exercise suspect code path repeatedly
  3. Take second snapshot
  4. Compare → look at "objects allocated between snapshots"
  5. Inspect retainer paths to find roots holding memory