Files
2nd/10_Wiki/Topics/DevOps_and_Security/V8 Engine.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

182 lines
5.6 KiB
Markdown

---
id: wiki-2026-0508-v8-engine
title: V8 Engine
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [V8, Chrome JavaScript Engine, Node.js Runtime Engine]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
verification_status: applied
tags: [v8, javascript, runtime, jit, engine]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: cpp
framework: v8
---
# V8 Engine
## 매 한 줄
> **"매 multi-tier JIT + generational GC 의 JavaScript runtime"**. 매 Google (2008) 의 Chrome 용 의 open-source 의 release 의 Node.js + Electron + Deno 의 ecosystem 의 substrate. 매 2026 년 의 V8 13.x 의 Maglev (mid-tier) + Turboshaft (top-tier) + sandbox + pointer-compression 의 modern stack.
## 매 핵심
### 매 execution pipeline (4-tier)
1. **Ignition** — bytecode interpreter. 매 startup fast.
2. **Sparkplug** — non-optimizing baseline JIT. 매 cheap compile.
3. **Maglev** — mid-tier optimizing JIT (V8 11.7+). 매 quick optimize.
4. **TurboFan / Turboshaft** — top-tier optimizing JIT. 매 peak perf.
### 매 memory subsystem
- **Pointer compression cage** (4GB).
- **Generational GC** — Scavenger (young) + Mark-Compact (old).
- **Concurrent + incremental** marking.
- **Heap spaces**: New, Old, Large object, Code, Map, etc.
### 매 응용
1. Browser JS (Chrome, Edge, Brave, Opera).
2. Server runtime (Node.js).
3. Desktop (Electron).
4. Edge / serverless (Cloudflare Workers, Vercel Edge — actually V8 isolates).
5. Embedded scripting (CouchDB, MongoDB shell).
## 💻 패턴
### Embed V8 in C++ (minimal hello)
```cpp
#include <v8.h>
#include <libplatform/libplatform.h>
int main(int argc, char* argv[]) {
v8::V8::InitializeICUDefaultLocation(argv[0]);
auto platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
v8::Isolate::CreateParams params;
params.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
v8::Isolate* isolate = v8::Isolate::New(params);
{
v8::Isolate::Scope iscope(isolate);
v8::HandleScope hscope(isolate);
auto ctx = v8::Context::New(isolate);
v8::Context::Scope cscope(ctx);
auto src = v8::String::NewFromUtf8Literal(isolate, "1 + 2");
auto script = v8::Script::Compile(ctx, src).ToLocalChecked();
auto result = script->Run(ctx).ToLocalChecked();
v8::String::Utf8Value utf8(isolate, result);
printf("%s\n", *utf8);
}
isolate->Dispose();
v8::V8::Dispose();
return 0;
}
```
### Inspect tier transitions (Node.js)
```bash
node --trace-opt --trace-deopt app.js
# Watch which functions get Turboshaft-optimized vs deoptimize
```
### Hidden class / inline cache friendly
```javascript
// GOOD — same shape every time → same hidden class → IC monomorphic
function Point(x, y) { this.x = x; this.y = y; }
const points = [new Point(1,2), new Point(3,4)];
// BAD — shape changes → IC megamorphic → slow
const p1 = {x:1, y:2};
const p2 = {x:1, y:2, z:3}; // different shape
```
### Snapshot for fast startup
```cpp
// Build a snapshot blob with pre-loaded JS, then restore it
v8::SnapshotCreator creator;
{
auto isolate = creator.GetIsolate();
v8::HandleScope hscope(isolate);
auto ctx = v8::Context::New(isolate);
v8::Context::Scope scope(ctx);
// run init JS...
creator.SetDefaultContext(ctx);
}
auto blob = creator.CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kClear);
// Save blob.data, load with v8::Isolate::CreateParams::snapshot_blob
```
### Isolate-per-request (Cloudflare Workers model)
```javascript
// Conceptual — V8 isolates as multi-tenant unit
class WorkerRunner {
async run(script, request) {
const isolate = new V8Isolate({ memoryLimit: 128_000_000 });
const ctx = isolate.createContext();
ctx.global.fetch = fetch;
try {
return await ctx.eval(script).fetch(request);
} finally {
isolate.dispose();
}
}
}
```
### Force GC + heap snapshot
```bash
node --expose-gc --inspect app.js
# In code: global.gc(); v8.writeHeapSnapshot('s.heapsnapshot');
```
### Tune for memory-constrained env
```bash
node --max-old-space-size=512 \
--max-semi-space-size=64 \
--optimize-for-size \
app.js
```
## 매 결정 기준
| 상황 | Tier / Setting |
|---|---|
| Cold start critical | Snapshot + Sparkplug |
| Steady-state CPU-bound | Let TurboFan/Turboshaft warm up |
| Memory-constrained | `--optimize-for-size` + lower max-old-space |
| Multi-tenant edge | One isolate per request |
| Native interop heavy | NAPI / N-API (stable ABI) |
**기본값**: 매 default flags 의 modern Node 의 OK; 매 measure 후 tune.
## 🔗 Graph
- 부모: [[JavaScript]] · [[JIT Compilation]]
- 변형: [[JavaScriptCore]]
- 응용: [[Node.js]] · [[Electron]] · [[Deno]] · [[Cloudflare Workers]]
- Adjacent: [[Garbage Collection]] · [[Chrome V8 Heap Analysis]] · [[Electron V8 Memory Cage]]
## 🤖 LLM 활용
**언제**: 매 perf debugging 의 deopt 의 reading. 매 hidden class 의 explanation. 매 flag selection.
**언제 X**: 매 V8 internal API 의 frequent change. 매 LLM 의 outdated 의 risk → release notes 의 verify.
## ❌ 안티패턴
- **Polymorphic shapes**: 매 IC megamorphic 의 cause. 매 hidden class consistent 의 keep.
- **Try/catch in hot loop (pre-V8 6)**: 매 modern V8 의 OK 지만 의 still 의 cost.
- **`delete` on hot object**: 매 hidden class transition 의 trigger.
- **Naive `eval`**: 매 deopt + security risk.
## 🧪 검증 / 중복
- Verified (V8 official docs, V8 blog 2026, Node.js v22+ docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 4-tier pipeline + 2026 modern stack (Maglev, Turboshaft) |