Working with V8 Module
1. Getting Heap Statistics (v8.getHeapStatistics)
| Field | Meaning |
|---|---|
total_heap_size | Heap allocated |
used_heap_size | Currently in use |
heap_size_limit | Maximum allowed |
malloced_memory | Native allocations |
peak_malloced_memory | Peak native allocs |
2. Getting Heap Space Statistics
| Space | Holds |
|---|---|
| new_space | Young generation (short-lived) |
| old_space | Long-lived objects |
| code_space | JIT code |
| map_space | Hidden classes |
| large_object_space | Big 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
| API | Use |
|---|---|
v8.serialize(obj) | Structured-clone Buffer |
v8.deserialize(buf) | Reverse |
| Supports | Maps, Sets, Dates, TypedArrays, BigInt |
5. Using Cached Data
| API | Use |
|---|---|
vm.Script.cachedData | Pre-compile JS for faster startup |
--use-snapshot / node:sea | Single-executable apps |
6. Setting Heap Limit (--max-old-space-size)
| Flag | Default |
|---|---|
--max-old-space-size=4096 | 4 GB old space |
--max-semi-space-size=128 | Young space size |
NODE_OPTIONS | Pass via env var |
7. Profiling Memory Usage
| Tool | Use |
|---|---|
| Heap snapshots | Compare 3 snapshots to find leaks |
--heap-prof | Sampling profile output |
v8.getHeapCodeStatistics | JIT code memory |
8. Understanding Garbage Collection
| Phase | Description |
|---|---|
| Scavenge (Minor) | Young space, fast and frequent |
| Mark-Sweep-Compact (Major) | Full heap, slower |
| Incremental marking | Splits work to reduce pauses |
| Concurrent marking | Runs alongside JS |
--expose-gc | Manually call global.gc() (debug only) |
9. Using Weak References
| API | Use |
|---|---|
WeakRef(obj) | Allow GC of target |
WeakMap / WeakSet | Keys can be GC'd |
FinalizationRegistry | Cleanup callback after GC |