[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,100 +1,168 @@
|
||||
---
|
||||
id: wiki-2026-0508-new-space-young-generation
|
||||
title: New Space(Young Generation)
|
||||
title: New Space (Young Generation)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-9FB32F]
|
||||
aliases: [Young Generation, Eden + Survivor, Scavenger, Minor GC, Nursery]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [gc, v8, jvm, generational-gc, memory-management]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - New Space(Young Generation)"
|
||||
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: C++
|
||||
framework: V8, HotSpot JVM, .NET
|
||||
---
|
||||
|
||||
# [[New Space(Young Generation)|New Space(Young Generation]]
|
||||
# New Space (Young Generation)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> V8 엔진의 메모리 힙(Heap) 구조 내에서 새롭게 생성된 객체들이 처음으로 할당되는 공간으로, 'Young Generation(젊은 세대)'이라고도 불린다 [1-3]. 대부분의 객체가 생성 직후 곧바로 접근 불가능해진다는 '세대 가설([[Generational Hypothesis|Generational Hypothesis]])'에 기반하여 설계되었기 때문에, 공간의 크기가 작고 가비지 컬렉션(GC)이 매우 빠르고 빈번하게 일어나는 것이 특징이다 [4-6]. 스캐빈저(Scavenger)라 불리는 마이너 GC(Minor GC)에 의해 공간이 관리되며, 특정 횟수 이상 살아남은 객체들은 [[Old Space|Old Space]](구세대)로 승격(Promotion)된다 [2, 4].
|
||||
## 매 한 줄
|
||||
> **"매 generational GC 의 short-lived object region"**. 매 1984 Lieberman & Hewitt 의 매 generational hypothesis ("most objects die young") 매 base. 매 V8 의 New Space (Scavenger), 매 JVM 의 Young Gen (Eden + 2 Survivor), 매 .NET 의 Gen 0/1 — 매 모두 매 동일한 idea: 매 young object 매 cheap copy + 매 old object 매 promote.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **할당 메커니즘과 메모리 구조:**
|
||||
New Space에서의 객체 할당은 할당 포인터(Allocation pointer)를 증가시키기만 하면 되므로 매우 빠른 속도를 자랑한다 [4, 7]. 이 공간은 매우 빠른 가비지 컬렉션을 위해 설계되어 일반적으로 1MB~64MB(행동 휴리스틱에 따라 1MB~8MB로도 언급됨)의 비교적 작은 크기로 유지된다 [4, 7]. New Space 내부의 객체는 세부적으로 새로 할당되는 'Nursery'와 한 번의 GC에서 살아남은 'Intermediate' 하위 세대로 나뉘며, 메모리 구조상 동일한 크기의 'From-Space'와 'To-Space'라는 두 개의 반공간(Semi-space)으로 분할된다 [8-10].
|
||||
## 매 핵심
|
||||
|
||||
* **마이너 GC (Scavenge) 작동 방식:**
|
||||
객체 할당 포인터가 New Space의 끝에 도달하여 공간이 가득 차게 되면 마이너 GC 주기인 '스캐빈지(Scavenge)'가 트리거된다 [4, 7]. 스캐빈저는 체니의 알고리즘(Cheney's algorithm)을 기반으로 작동하며, From-Space에서 여전히 참조되고 있는 살아있는(live) 객체만을 식별하여 빈 공간인 To-Space로 복사(대피)시킨다 [7, 8, 10, 11]. 복사가 완료되면 From-Space의 나머지 데이터는 가비지로 간주되어 전부 비워지며, 이후 From-Space와 To-Space의 역할이 서로 뒤바뀐다 [11, 12]. 이 과정에서 객체들이 연속된 메모리 블록으로 압축(Compaction)되므로 메모리 단편화가 완전히 해소된다 [8, 11].
|
||||
### 매 generational hypothesis
|
||||
- 매 90%+ object 매 매 first GC cycle 의 die.
|
||||
- 매 survivor 매 long-lived 가능 매 high.
|
||||
- 매 separate region + 매 separate algorithm 매 efficient.
|
||||
|
||||
* **객체의 승격 (Promotion):**
|
||||
Nursery에 할당된 객체가 첫 번째 마이너 GC에서 살아남으면 Intermediate 상태가 되어 새로운 페이지(To-Space)로 이동한다 [9, 13]. 스캐빈지 과정을 두 번 거치고도 살아남은 객체들은 수명이 긴 객체로 판단되어 New Space를 떠나 Old Generation(Old Space)으로 승격된다 [4, 9, 11].
|
||||
### 매 V8 New Space 구조
|
||||
- 매 to-space + from-space (semispace).
|
||||
- 매 Cheney's Scavenge (Cheney 1970) — 매 BFS copy.
|
||||
- 매 size 매 1-8MB per isolate (V8 12+ adaptive).
|
||||
- 매 minor GC: 매 < 1ms typical.
|
||||
- 매 promotion: 매 2회 survive 시 Old Space 로 이동.
|
||||
|
||||
* **튜닝 및 크기 제어:**
|
||||
Node.js 환경에서는 V8 플래그를 통해 New Space의 크기를 조절할 수 있다. `--min_semi_space_size` 및 `--max_semi_space_size` (또는 `--max-semi-space-size`) 옵션을 사용하면 이 공간의 크기를 명시적으로 제어할 수 있다 [3, 14]. 트래픽이 많거나 생성 후 곧바로 소멸하는 소규모 객체가 매우 자주 생성되는 애플리케이션의 경우, New Space 크기를 늘려 마이너 GC의 발생 빈도를 줄이고 전반적인 성능 저하를 방지할 수 있다 [14].
|
||||
### 매 JVM Young Gen 구조
|
||||
- 매 Eden (allocation site) + Survivor 0 + Survivor 1.
|
||||
- 매 Eden full → 매 minor GC → 매 live → S0 (or S1).
|
||||
- 매 매 매 Tenuring threshold (default 15) 도달 → Old Gen.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 응용
|
||||
1. JS engine (V8 / SpiderMonkey / JavaScriptCore).
|
||||
2. JVM (HotSpot G1, ZGC, Parallel).
|
||||
3. .NET CLR.
|
||||
4. Dart VM.
|
||||
5. Lua의 incremental (slightly different).
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** Minor GC(Scavenger), [[Old Space(Old Generation)|Old Space(Old Generation]], [[Generational Hypothesis|Generational Hypothesis]], Semi-space Design
|
||||
- **Projects/Contexts:** [[V8 JavaScript Engine|V8 JavaScript Engine]], Node.js memory [[Management|Management]]
|
||||
- **Contradictions/Notes:** 소스 간에 New Space의 일반적인 크기 범위에 대한 서술에 약간의 차이가 존재합니다. 소스 [4]은 행동 휴리스틱에 따라 "1MB에서 8MB 사이"라고 명시하지만, 소스 [7]은 "일반적으로 1MB에서 64MB 사이"로 다소 더 큰 범위를 제시합니다.
|
||||
## 💻 패턴
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-19*
|
||||
### 1. V8 heap snapshot 측정
|
||||
```ts
|
||||
import v8 from 'node:v8';
|
||||
|
||||
---
|
||||
|
||||
## 🤖 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
|
||||
const stats = v8.getHeapSpaceStatistics();
|
||||
const newSpace = stats.find(s => s.space_name === 'new_space');
|
||||
console.log({
|
||||
size: newSpace.space_size,
|
||||
used: newSpace.space_used_size,
|
||||
available: newSpace.space_available_size,
|
||||
});
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 2. V8 GC trace flag
|
||||
```bash
|
||||
node --trace-gc app.js
|
||||
# [12345:0x1234] 234 ms: Scavenge 4.5 (5.3) -> 0.8 (5.3) MB, 1.2 ms
|
||||
node --trace-gc-verbose --max-semi-space-size=64 app.js
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### 3. Allocation site 의 promotion 회피
|
||||
```ts
|
||||
// 매 hot loop 의 ephemeral 의 ㅇ
|
||||
function processStream(items: Item[]) {
|
||||
for (const item of items) {
|
||||
const tmp = { x: item.x * 2, y: item.y * 2 }; // 매 New Space alloc
|
||||
emit(tmp); // 매 die immediately — minor GC 의 reclaim
|
||||
}
|
||||
}
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// 매 X — 매 long-lived array 의 promotion
|
||||
const cache: Record<string, Result> = {};
|
||||
function bad(item: Item) {
|
||||
cache[item.id] = compute(item); // 매 Old Space promotion
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### 4. JVM Young Gen tuning
|
||||
```bash
|
||||
java -Xms2g -Xmx8g \
|
||||
-XX:NewRatio=2 \
|
||||
-XX:SurvivorRatio=8 \
|
||||
-XX:MaxTenuringThreshold=10 \
|
||||
-XX:+UseG1GC \
|
||||
-Xlog:gc*:file=gc.log \
|
||||
App
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### 5. Pretenuring (object 의 사전 Old 배치)
|
||||
```cpp
|
||||
// V8 internal: AllocationSite 가 매 history 추적 → 매 large/long-lived 매 immediate Old.
|
||||
// 매 user-facing API X — 매 V8 의 implicit.
|
||||
// 매 application 의 hint: 매 reuse object pool.
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### 6. Object pool (allocation pressure 회피)
|
||||
```ts
|
||||
class Vec3Pool {
|
||||
private pool: Vec3[] = [];
|
||||
acquire(): Vec3 {
|
||||
return this.pool.pop() ?? new Vec3();
|
||||
}
|
||||
release(v: Vec3) {
|
||||
v.set(0, 0, 0);
|
||||
if (this.pool.length < 1000) this.pool.push(v);
|
||||
}
|
||||
}
|
||||
// 매 매 frame 의 allocation 의 X → minor GC 매 silent
|
||||
```
|
||||
|
||||
### 7. .NET Gen 0 stats
|
||||
```csharp
|
||||
GC.Collect(0); // 매 Gen 0 (Young) 매 only
|
||||
Console.WriteLine($"Gen0: {GC.CollectionCount(0)}");
|
||||
Console.WriteLine($"Gen1: {GC.CollectionCount(1)}");
|
||||
Console.WriteLine($"Gen2: {GC.CollectionCount(2)}");
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | New Space tuning |
|
||||
|---|---|
|
||||
| Allocation-heavy (web server) | 매 large New Space (V8 64-256MB) — 매 Scavenge frequency 줄임 |
|
||||
| Long-lived state (cache) | 매 small New Space — 매 promote fast |
|
||||
| Latency-critical (game) | 매 object pool + 매 zero-alloc hot path |
|
||||
| Memory-tight (mobile) | 매 default + GC tuning 의 X |
|
||||
| Long debugging session | --trace-gc + heap snapshot |
|
||||
|
||||
**기본값**: 매 V8 default New Space + 매 hot path 의 object pool 사용.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Garbage Collection]] · [[Generational GC]]
|
||||
- 변형: [[Old Space]] · [[Mark-Sweep-Compact]] · [[Eden Space]] · [[Survivor Space]]
|
||||
- 응용: [[V8 GC]] · [[HotSpot G1]] · [[ZGC]] · [[.NET CLR GC]]
|
||||
- Adjacent: [[Cheney's Algorithm]] · [[Tenuring]] · [[Allocation Site]] · [[Object Pool]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 GC pause 매 SLO 위협. 매 allocation profiling 매 hot path 식별. 매 V8 / JVM heap behavior 의 understanding.
|
||||
**언제 X**: 매 Rust / C++ (no GC). 매 small script (default 면 충분). 매 micro-optimization 의 매 measurement 의 X.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **매 frame 의 새 closure**: 매 frame 마다 매 object alloc → 매 Scavenge 폭발.
|
||||
- **Long-lived array 의 매 push/splice**: 매 internal buffer 의 New Space alloc → promote.
|
||||
- **TypedArray 의 매 매 new 만들기**: 매 reuse — 매 Float32Array 매 large allocation.
|
||||
- **매 GC 의 force (`global.gc()`)**: 매 production 의 X — 매 V8 heuristic 의 disrupt.
|
||||
- **매 NewRatio 매 production 의 변경 의 측정 없이**: 매 application-specific tuning — default 매 first.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (V8 design docs 2026-05, OpenJDK HotSpot source, Cheney 1970 paper).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Cheney scavenge + V8/JVM/.NET cross-platform comparison |
|
||||
|
||||
Reference in New Issue
Block a user