[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,93 +2,169 @@
|
||||
id: wiki-2026-0508-scavenger-알고리즘
|
||||
title: Scavenger 알고리즘
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-04124F]
|
||||
aliases: [V8 Scavenger, Minor GC, Young Generation GC, Cheney Algorithm]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [v8, javascript-engine, garbage-collection, gc, performance]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - [[Scavenge|Scavenge]]r 알고리즘"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: JavaScript
|
||||
framework: V8 / Node.js
|
||||
---
|
||||
|
||||
# [[Scavenger 알고리즘|Scavenger 알고리즘]]
|
||||
# Scavenger 알고리즘
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> Scavenger 알고리즘은 V8 [[JavaScript|JavaScript]] 엔진에서 새로운 객체가 주로 할당되는 '새로운 공간(New-space)'의 가비지를 수집하는 마이너 가비지 컬렉션(Minor GC) 알고리즘입니다 [1-3]. 이 알고리즘은 공간을 두 개의 동일한 크기(to-space와 from-space)로 나누고 살아남은 활성 객체만 새로운 공간으로 복사하여 압축하는 세미스페이스(semi-space) 방식을 통해 메모리 단편화를 방지하고 매우 빠르게 메모리를 회수합니다 [3-5]. 최근의 V8 엔진에서는 [[Orinoco|Orinoco]] 프로젝트를 통해 메인 스레드와 헬퍼 스레드에 작업을 분산시키는 병렬(Parallel) 방식으로 진화하여 메인 스레드의 일시 정지 시간을 획기적으로 단축시켰습니다 [6-8].
|
||||
## 매 한 줄
|
||||
> **"매 Scavenger 는 V8 의 minor GC — semi-space copying collector for short-lived objects"**. Cheney's algorithm 기반, young generation (new space) 을 from-space / to-space 로 나눠 매 minor GC 마다 live object 만 to-space 로 복사. Survivor 는 old space 로 promote. 매 fast (수 ms), 매 web app 의 hot path. Major GC (Mark-Sweep-Compact) 와 분리.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **세미스페이스(Semi-space) 설계 및 작동 원리:** V8의 새로운 공간(New-space 혹은 Young generation)은 Cheney의 알고리즘에 기반하여 'to-space'와 'from-space'라는 두 개의 동일한 크기의 세미스페이스로 나뉩니다 [3-5, 9]. 메모리 할당은 할당 포인터를 증가시키는 방식으로 빠르게 이루어지며, 할당 포인터가 공간의 끝에 도달하여 메모리가 부족해지면 Scavenge 주기가 트리거됩니다 [1, 5, 10].
|
||||
* **활성 객체 대피(Evacuation) 및 압축(Compaction):** 가비지 컬렉션이 시작되면 루트 객체로부터 도달 가능한 활성 객체를 식별한 뒤, 이들을 from-space에서 to-space로 복사(대피)합니다 [3-5, 11]. 이 과정에서 객체들이 연속된 메모리 블록으로 압축되므로 캐시 지역성이 향상되고 메모리 단편화(Fragmentation)가 완전히 제거됩니다 [4, 11, 12]. 복사가 완료되면 남은 from-space의 데이터는 모두 가비지로 간주되어 버려지며, 두 공간의 역할이 교체됩니다 [11-15].
|
||||
* **세대 가설에 따른 객체 승격 (Promotion):** Scavenger 알고리즘은 대부분의 객체가 일찍 소멸한다는 '세대 가설([[Generational Hypothesis|Generational Hypothesis]])'을 바탕으로 설계되었습니다 [1, 16]. 따라서 Scavenge 주기를 두 번 생존한 객체는 더 이상 새로운 공간에 머물지 않고 장기 보관을 위해 '오래된 공간(Old-space)'으로 승격(Promoted)됩니다 [1, 11, 17, 18].
|
||||
* **쓰기 장벽 ([[Write Barrier|Write Barrier]]s)의 활용:** 오래된 공간(Old-space)의 객체가 새로운 공간(New-space)의 객체를 참조하는 경우를 식별하기 위해, V8은 전체 오래된 공간을 스캔하는 대신 '쓰기 장벽(Write Barriers)'을 활용하여 참조 포인터의 위치를 기억 집합(Store buffer 또는 Remembered set)에 기록합니다 [12, 14, 15, 19]. 이를 통해 Scavenge 수행 시 스캔 비용을 획기적으로 낮춥니다 [12, 14].
|
||||
* **병렬 처리 (Parallel Scavenger):** 과거에는 Cheney 알고리즘을 사용한 단일 스레드 방식으로 동작했으나, 멀티코어 환경에 맞춰 V8(Orinoco 가비지 콜렉터)은 '병렬 Scavenger(Parallel Scavenger)'를 도입했습니다 [7, 20]. 메인 스레드와 여러 헬퍼 스레드가 포인터를 나누어 추적하고 동적으로 작업 훔치기(work stealing)를 수행하여, 결과적으로 메인 스레드에서 Scavenger가 소모하는 시간을 20%~50% 감소시켰습니다 [7, 8, 20, 21].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 generational hypothesis
|
||||
- 대부분 객체는 young 일 때 die → 매 young 만 자주 GC 하면 효율
|
||||
- V8 heap: new space (young, ~16MB) + old space (long-lived) + large object space + code/map space
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** Minor GC, Young Generation, Cheney's Algorithm, Write Barriers, [[Orinoco|Orinoco]]
|
||||
- **Projects/Contexts:** V8 엔진 메모리 관리 (V8 [[memory|memory]] [[Management|Management]]), 가비지 컬렉션 최적화
|
||||
- **Contradictions/Notes:** 과거 버전의 V8에서는 Scavenger가 단일 코어 환경에 적합한 완전한 동기식 Cheney 알고리즘을 구현했으나, 현재 크롬 및 Node.js의 멀티코어 환경 요구에 맞추어 메인 스레드와 워커 스레드가 동적으로 작업을 분배하는 병렬(Parallel) 복사 가비지 컬렉터로 진화했음이 기록되어 있습니다 [10, 20].
|
||||
### 매 Cheney's copying
|
||||
- new space = from-space + to-space (반반)
|
||||
- minor GC: from-space 의 live root → to-space 로 BFS-copy
|
||||
- 매 dead object 은 자동 폐기 (sweep 불필요)
|
||||
- 두번째 survival 시 old space 로 promote
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-19*
|
||||
### 매 비용
|
||||
- O(live data) — dead 가 많으면 매우 빠름
|
||||
- pause time: 매 1-5ms (web app)
|
||||
- write barrier: old → new pointer 추적 (remembered set)
|
||||
|
||||
---
|
||||
### 매 응용
|
||||
1. Allocation-heavy code path 의 GC pressure 분석.
|
||||
2. Hot loop 에서 전혀 다른 object 양산 회피.
|
||||
3. Node.js memory profile (`--trace-gc`).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### Trace GC events
|
||||
```bash
|
||||
node --trace-gc app.js
|
||||
# [pid] 12 ms: Scavenge 4.5 (5.7) -> 0.8 (5.7) MB, 0.3 / 0.0 ms
|
||||
# [pid] 45 ms: Mark-sweep 5.0 (10.2) -> 2.1 (10.2) MB, 4.8 / 0.0 ms
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Detailed GC trace
|
||||
```bash
|
||||
node --trace-gc-verbose --trace-gc-nvp app.js
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Heap snapshot (Chrome DevTools 연결)
|
||||
```typescript
|
||||
import { writeHeapSnapshot } from "node:v8";
|
||||
const file = writeHeapSnapshot();
|
||||
console.log(`매 snapshot at ${file}`);
|
||||
// load in DevTools → Memory tab → Compare snapshots
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Avoid allocation in hot loop
|
||||
```typescript
|
||||
// 매 BAD — 매 iteration creates objects
|
||||
function sumPoints(points: { x: number; y: number }[]): number {
|
||||
return points
|
||||
.map((p) => ({ ...p, sum: p.x + p.y })) // new objects
|
||||
.reduce((a, b) => a + b.sum, 0);
|
||||
}
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
// 매 GOOD — 매 no allocation in loop
|
||||
function sumPointsFast(points: { x: number; y: number }[]): number {
|
||||
let s = 0;
|
||||
for (let i = 0; i < points.length; i++) s += points[i].x + points[i].y;
|
||||
return s;
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Object pool to bypass GC
|
||||
```typescript
|
||||
class Vec3Pool {
|
||||
private pool: { x: number; y: number; z: number }[] = [];
|
||||
acquire(x = 0, y = 0, z = 0) {
|
||||
const v = this.pool.pop() ?? { x: 0, y: 0, z: 0 };
|
||||
v.x = x; v.y = y; v.z = z;
|
||||
return v;
|
||||
}
|
||||
release(v: { x: number; y: number; z: number }) {
|
||||
this.pool.push(v);
|
||||
}
|
||||
}
|
||||
const pool = new Vec3Pool();
|
||||
const v = pool.acquire(1, 2, 3);
|
||||
pool.release(v);
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Measure GC pause via PerformanceObserver
|
||||
```typescript
|
||||
import { PerformanceObserver } from "node:perf_hooks";
|
||||
|
||||
const obs = new PerformanceObserver((list) => {
|
||||
for (const entry of list.getEntries()) {
|
||||
console.log(`매 GC ${entry.detail?.kind} took ${entry.duration.toFixed(2)}ms`);
|
||||
}
|
||||
});
|
||||
obs.observe({ entryTypes: ["gc"], buffered: true });
|
||||
```
|
||||
|
||||
### Tune new space size
|
||||
```bash
|
||||
node --max-semi-space-size=64 app.js # default ~16MB, increase for alloc-heavy
|
||||
node --max-old-space-size=4096 app.js # old gen
|
||||
```
|
||||
|
||||
### Detect promotion pressure
|
||||
```typescript
|
||||
import v8 from "node:v8";
|
||||
setInterval(() => {
|
||||
const stats = v8.getHeapSpaceStatistics();
|
||||
for (const s of stats) {
|
||||
console.log(`${s.space_name}: ${(s.space_used_size / 1e6).toFixed(1)} MB`);
|
||||
}
|
||||
}, 5000);
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Short-lived 객체 많음 (정상) | Scavenger 가 처리 — 신경 X |
|
||||
| Hot loop allocation 폭주 | 매 reuse / pool / typed arrays |
|
||||
| Old space 증가 (leak 의심) | heap snapshot + retainer 분석 |
|
||||
| Long pause (>50ms) | major GC 문제 — incremental marking 확인 |
|
||||
| Alloc-heavy server | `--max-semi-space-size` 증가 |
|
||||
|
||||
**기본값**: 매 normal code 는 Scavenger 가 자동 처리. 매 hot path 는 alloc-free 하게 작성.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[V8 Engine]] · [[Garbage Collection]] · [[JavaScript Runtime]]
|
||||
- 변형: [[Mark-Sweep-Compact]] · [[Incremental Marking]] · [[Concurrent Marking]] · [[Orinoco]]
|
||||
- 응용: [[Node.js Performance]] · [[V8 Heap Snapshots]] · [[Object Pools]]
|
||||
- Adjacent: [[Cheney Algorithm]] · [[Generational GC]] · [[Hidden Classes]] · [[Inline Caches]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: V8 GC 설명, Node.js memory tuning, hot-path optimization. 매 `--trace-gc` output 해석.
|
||||
**언제 X**: 매 일반 web/app code review (premature opt 우려). 매 non-V8 runtime (Bun is JSC fork? actually JSCore — 다른 GC).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **GC tuning premature**: 매 measure 없이 flag 변경. 매 profile 먼저.
|
||||
- **Manual `global.gc()`**: 매 production 에서 `--expose-gc` 의존 — 매 anti-pattern.
|
||||
- **Object literal in hot loop**: GC pressure 증가. 매 reuse / pool.
|
||||
- **Megamorphic shapes**: 매 hidden class 변형 → IC miss → 추가 alloc. 매 shape 일정.
|
||||
- **Closures in loop**: 매 iteration 마다 closure 생성 → young heap pressure.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (V8 blog, "Trash talk: the Orinoco garbage collector", 2016 + later updates).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — V8 Scavenger algorithm full content |
|
||||
|
||||
Reference in New Issue
Block a user