--- id: wiki-2026-0508-v8-engine-heap-management title: V8 Engine Heap Management category: 10_Wiki/Topics status: verified canonical_id: self aliases: [V8 Heap, V8 Memory Layout, V8 Sandbox] duplicate_of: none source_trust_level: A confidence_score: 0.9 verification_status: applied tags: [v8, javascript, memory, runtime, gc] raw_sources: [] last_reinforced: 2026-05-10 github_commit: pending tech_stack: language: C++/JavaScript framework: V8 --- # V8 Engine Heap Management ## 매 한 줄 > **"매 generational heap + sandbox + pointer compression"**. V8 매 Young/Old Gen 의 분리 + Orinoco GC + 매 4GB sandbox 의 OOB exploit 의 mitigate. 2026 매 V8 12.x — 매 Maglev tier + Sparkplug + sandbox-by-default + Node.js 22 LTS. ## 매 핵심 ### 매 Heap 구조 - **Young Generation** — 매 short-lived: Nursery (To/From semi-space) + Intermediate. - **Old Generation** — 매 long-lived: Old Pointer Space + Old Data Space. - **Large Object Space** — 매 >256KB allocations. - **Code Space** — 매 JIT-compiled machine code. - **Map Space** — 매 hidden classes (V8 Maps). - **Read-Only Space** — 매 immutable VM-level data. ### 매 GC 알고리즘 - Scavenger (Young): Cheney's copying — 매 minor GC, 매 ms 단위. - Major GC (Old): Mark-Sweep-Compact + concurrent/parallel/incremental. - Orinoco — main-thread pause 의 minimize. ### 매 V8 Sandbox (Memory Cage) - 매 V8 heap 의 4GB virtual region 의 confine. - 매 internal pointer 의 sandbox-relative 32-bit offset. - 매 OOB write exploit 의 host process corrupt X. - 매 V8 11.4+ default — 매 `--sandbox` flag. ### 매 Pointer Compression - 매 64-bit isolate 의 32-bit offset 사용 (4GB heap). - 매 메모리 의 ~40% 절감. - Cage base register + offset = full pointer. ### 매 Hidden Classes (Maps) - 매 object shape descriptor. - 매 inline cache (IC) 의 fast property access. - 매 shape transition 의 monomorphic 유지 의 핵심. ### 매 응용 1. Node.js memory tuning — `--max-old-space-size`. 2. Memory leak debugging — heap snapshot. 3. JIT optimization — monomorphic code path. 4. Embedded V8 — Deno, Cloudflare Workers, Electron. ## 💻 패턴 ### Heap size tuning ```bash # 4GB old generation node --max-old-space-size=4096 server.js # 256MB young generation (semi-space) node --max-semi-space-size=128 worker.js ``` ### Heap snapshot — memory leak detection ```javascript import { writeHeapSnapshot } from "node:v8"; setInterval(() => { const path = writeHeapSnapshot(`./heap-${Date.now()}.heapsnapshot`); console.log("Heap snapshot:", path); }, 60_000); ``` ### `process.memoryUsage` ```javascript const m = process.memoryUsage(); console.log({ rss: (m.rss / 1024 / 1024).toFixed(1) + " MB", heapUsed: (m.heapUsed / 1024 / 1024).toFixed(1) + " MB", heapTotal: (m.heapTotal / 1024 / 1024).toFixed(1) + " MB", external: (m.external / 1024 / 1024).toFixed(1) + " MB", }); ``` ### V8 stats — getHeapStatistics ```javascript import { getHeapStatistics, getHeapSpaceStatistics } from "node:v8"; console.log(getHeapStatistics()); // total_heap_size, used_heap_size, heap_size_limit, ... for (const space of getHeapSpaceStatistics()) { console.log(space.space_name, space.space_used_size); } ``` ### Monomorphic vs polymorphic — IC friendly ```javascript // GOOD — same shape every call → monomorphic IC function area({ w, h }) { return w * h; } area({ w: 1, h: 2 }); area({ w: 3, h: 4 }); // BAD — varied shapes → megamorphic, IC miss area({ w: 1, h: 2, label: "a" }); area({ w: 3, h: 4, color: "red" }); ``` ### Hidden class stability ```javascript // BAD — late property addition forces shape transition const u = {}; u.id = 1; u.name = "x"; // GOOD — initialize all properties at construction const u2 = { id: 1, name: "x" }; ``` ### `--prof` + `--prof-process` ```bash node --prof app.js # Generates isolate-*.log node --prof-process isolate-*.log > prof.txt ``` ### WeakRef — manual lifecycle ```javascript const cache = new Map(); function get(key) { const ref = cache.get(key); const val = ref?.deref(); if (val) return val; const fresh = expensive(key); cache.set(key, new WeakRef(fresh)); return fresh; } ``` ## 매 결정 기준 | 상황 | Approach | |---|---| | Default Node.js | 매 V8 default — 충분. | | Memory-heavy worker | `--max-old-space-size=8192`. | | Latency-sensitive | 매 short-lived alloc 의 Young Gen 유지 — small heap. | | Memory leak suspect | `writeHeapSnapshot` + Chrome DevTools. | | Hot loop | Monomorphic shape — 매 동일 hidden class. | | Embedded V8 | Sandbox enable + isolate per tenant. | **기본값**: 매 V8 default GC + sandbox enabled + monomorphic code + heap snapshot 의 production 의 leak 의 trigger 시. ## 🔗 Graph - 변형: [[V8 가비지 컬렉션(Garbage Collection)]] · [[V8 메모리 케이지(V8 Memory Cage)]] · [[To Space와 From Space]] - 응용: [[Node.js Performance]] · [[Cloudflare Workers]] - Adjacent: [[Garbage Collection]] · [[Hidden Class]] ## 🤖 LLM 활용 **언제**: Node.js 의 production tuning, memory leak diagnosis, JIT optimization, V8 embedding. **언제 X**: 매 SpiderMonkey/JavaScriptCore 의 generic 적용 X — 매 V8-specific. ## ❌ 안티패턴 - **매 late property addition**: hidden class transition — IC miss. - **매 too-small `--max-old-space-size`**: OOM crash. - **매 too-large heap**: GC pause 의 증가. - **매 closure 의 long-lived ref 유지**: 매 leak. - **매 megamorphic call site**: deopt → slow path. - **매 sandbox disable (`--no-sandbox`)**: 매 production 의 X. ## 🧪 검증 / 중복 - Verified (V8 blog, "Trash Talk" 시리즈; Orinoco design doc; V8 Sandbox RFC). - 신뢰도 A. ## 🕓 Changelog | 날짜 | 변경 | |---|---| | 2026-05-08 | Phase 1 | | 2026-05-10 | Manual cleanup — V8 heap 구조 + sandbox + GC + IC 패턴 정리 |