[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+161 -65
View File
@@ -2,93 +2,189 @@
id: wiki-2026-0508-buffer-allocation
title: Buffer Allocation
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-B20BA9]
aliases: [ArrayBuffer Allocation, Typed Array Pool]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [performance, memory, buffer, typed-array, gc]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Buffer Allocation"
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/TypeScript
framework: Browser/Node/WebGPU
---
# [[Buffer Allocation|Buffer Allocation]]
# Buffer Allocation
## 📌 한 줄 통찰 (The Karpathy Summary)
> 버퍼 할당(Buffer Allocation)[[WebGL|WebGL]] 및 [[WebGPU|WebGPU]] 환경에서 정점, 인덱스, 인스턴스 변환 행렬 등의 데이터를 저장하기 위해 GPU 메모리 공간을 확보하는 과정입니다. 렌더링 중 동적으로 버퍼 크기를 늘리거나 빈번하게 데이터를 업데이트할 경우 심각한 프레임 지연 및 메모리 오류가 발생할 수 있습니다. 따라서 최대 예상치에 맞춰 사전에 버퍼를 할당하고, 재사용 가능한 영구적인 GPU 버퍼를 활용하는 것이 3D 애플리케이션 성능 최적화에 필수적입니다.
## 한 줄
> **"매 buffer 매 reuse 매 GC 의 X"**. Buffer allocation은 binary data buffer (ArrayBuffer / Typed Array)의 effective lifecycle 관리 — naive `new Uint8Array(N)` per operation은 GC churn을 유발해 frame budget을 깬다. 2026 WebGPU / WebCodecs / canvas heavy app 의 must-skill.
## 📖 구조화된 지식 (Synthesized Content)
* **동적 버퍼 확장의 성능 병목 현상:** 인스턴싱([[Instancing|Instancing]]) 시스템이 초기에 낮은 버퍼 용량으로 시작하여 런타임에 동적으로 크기를 확장(Growing Buffer)하게 되면, 심각한 성능 지연(예: 앱 시작 시 수 초간의 멈춤 현상) 및 메모리 할당 오류가 발생할 수 있습니다 [1, 2].
* **최대 용량 사전 할당 (Preallocation):** 이를 방지하기 위해 엔진 시작 시점에 예상되는 최대 인스턴스 수에 맞춰 충분한 크기의 버퍼를 사전에 할당하는 방식이 권장됩니다 [1]. 여유 용량(Excess capacity)을 미리 확보하는 것은 약간의 메모리 오버헤드를 발생시키지만, 실제 렌더링 연산 비용에는 부정적인 영향을 주지 않습니다 [3].
* **GPU 영구 버퍼 및 업데이트 최소화:** WebGPU 환경에서 매 프레임 수많은 작은 버퍼를 반복 업데이트하는 것은 비용이 매우 큽니다 [4]. 따라서 `[[instancedArray|instancedArray]]`와 같은 영구적인 GPU 버퍼를 생성하여 사용하면 프레임 간 데이터가 유지되어, 성능 저하의 주원인인 CPU-GPU 간의 데이터 전송을 제거할 수 있습니다 [4, 5].
* **오브젝트 풀링(Object [[Pooling|Pooling]]) 활용:** 객체를 빈번하게 생성하고 파괴하는 작업은 버퍼 할당 오버헤드와 가비지 컬렉션(GC)에 의한 일시 정지를 유발합니다. 런타임 할당 스파이크를 피하려면 로딩 단계에서 풀을 미리 데워두는(Pre-warm) 방식의 오브젝트 풀링을 사용해야 합니다 [6].
* **버퍼 재할당 시 메모리 누수 주의:** WebGL 컨텍스트는 디바이스에 따라 유한한 메모리 한도(일반적으로 256MB~1GB)를 가지며, 한도를 초과하면 뷰어가 다운될 수 있습니다 [7]. 또한, 기존의 인스턴스 메쉬 자원을 깔끔하게 폐기(Dispose)하지 못한 상태에서 동적으로 버퍼 용량을 늘리려 할 경우 메모리 누수가 발생할 수 있습니다 [8].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 cost source
- **Allocation**: V8/SpiderMonkey backing-store malloc + zero-fill.
- **GC**: large allocation → Old-gen → expensive sweep.
- **Cache miss**: 매 fresh memory 의 cold cache.
- **Fragmentation**: many sizes → heap 의 fragmented.
## 🔗 지식 연결 (Graph)
- **Related Topics:** GPU Instancing, [[Memory Management|Memory Management]], Object Pooling, [[Garbage Collection|Garbage Collection]]
- **Projects/Contexts:** Three.js, [[Needle Engine|Needle Engine]], [[WebGPU|WebGPU]]
- **Contradictions/Notes:** 소스에서는 실행 중 버퍼 크기를 동적으로 늘리는 방식(Dynamic Growth)은 성능 지연과 오류를 낳으므로, 초기에 넉넉하게 메모리 공간을 사전 할당(Preallocate)하는 방식이 훨씬 안정적이라고 강조합니다 [1-3].
### 매 strategy
- **Pool / freelist**: 매 size class 매 reuse.
- **Subarray view**: single big buffer + slice views.
- **Pre-allocation**: peak size 부터 allocate.
- **SharedArrayBuffer**: cross-thread, no copy.
---
*Last updated: 2026-04-19*
### 매 응용
1. Audio / video frame buffer.
2. WebGL / WebGPU vertex / index buffer.
3. WebSocket binary message parser.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### Simple buffer pool
```ts
class BufferPool {
private pool: Uint8Array[] = [];
constructor(private size: number, private max = 32) {}
**언제 이 지식을 쓰는가:**
- *(TODO)*
acquire(): Uint8Array {
return this.pool.pop() ?? new Uint8Array(this.size);
}
**언제 쓰면 안 되는가:**
- *(TODO)*
release(buf: Uint8Array) {
if (this.pool.length < this.max) {
buf.fill(0);
this.pool.push(buf);
}
}
}
## 🧪 검증 상태 (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 pool = new BufferPool(4096);
const b = pool.acquire();
// use ...
pool.release(b);
```
## 🤔 의사결정 기준 (Decision Criteria)
### Size-class pool
```ts
class SizeClassPool {
private classes = new Map<number, Uint8Array[]>();
**선택 A를 써야 할 때:**
- *(TODO)*
private classOf(n: number): number {
return Math.pow(2, Math.ceil(Math.log2(Math.max(n, 16))));
}
**선택 B를 써야 할 때:**
- *(TODO)*
acquire(n: number): Uint8Array {
const cls = this.classOf(n);
const list = this.classes.get(cls);
return (list?.pop() ?? new Uint8Array(cls)).subarray(0, n);
}
**기본값:**
> *(TODO)*
release(buf: Uint8Array) {
const cls = buf.buffer.byteLength;
if (!this.classes.has(cls)) this.classes.set(cls, []);
this.classes.get(cls)!.push(new Uint8Array(buf.buffer));
}
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Single backing buffer + views
```ts
const big = new ArrayBuffer(1024 * 1024); // 1MB
const headers = new Uint32Array(big, 0, 256); // 1KB header
const body = new Uint8Array(big, 1024, 1024 * 1023); // remainder
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### WebSocket binary parsing — no copy
```ts
ws.binaryType = 'arraybuffer';
ws.onmessage = (e: MessageEvent<ArrayBuffer>) => {
const dv = new DataView(e.data);
const type = dv.getUint8(0);
const length = dv.getUint32(1, true);
const payload = new Uint8Array(e.data, 5, length);
handle(type, payload);
};
```
### SharedArrayBuffer ring buffer (worker comms)
```ts
// main
const sab = new SharedArrayBuffer(1024);
const view = new Int32Array(sab);
worker.postMessage(sab);
// worker — Atomics 매 lock-free synchronization
self.onmessage = (e) => {
const view = new Int32Array(e.data);
Atomics.store(view, 0, 42);
Atomics.notify(view, 0, 1);
};
```
### Reusable canvas pixel buffer
```ts
class FrameRecycler {
private buffers: ImageData[] = [];
acquire(w: number, h: number) {
return this.buffers.find(b => b.width === w && b.height === h)
?? new ImageData(w, h);
}
release(b: ImageData) {
if (this.buffers.length < 4) this.buffers.push(b);
}
}
```
### Detecting allocation hot spots
```ts
// 매 dev-only — 매 wrap allocator 매 trace
const _orig = Uint8Array;
let count = 0;
(globalThis as any).Uint8Array = function (...args: any[]) {
count++;
if (count % 1000 === 0) console.warn('Uint8Array allocations:', count);
return new _orig(...args);
};
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Per-frame temp buffer | pool with size class |
| Streaming binary protocol | preallocated parser buffer |
| Cross-thread share | SharedArrayBuffer + Atomics |
| GPU upload | persistent GPU buffer + map/unmap |
| Rare large alloc | direct allocate |
**기본값**: measure GC pressure first; pool only when allocator shows up in profile.
## 🔗 Graph
- 부모: [[Memory Management]] · [[Performance]]
- 변형: [[Object Pool]] · [[Arena Allocation]]
- 응용: [[WebGPU]] · [[WebCodecs]] · [[WebSocket]]
- Adjacent: [[SharedArrayBuffer]] · [[Typed Array]] · [[Garbage Collection]]
## 🤖 LLM 활용
**언제**: pool implementation scaffold, view layout calculation, ring buffer design.
**언제 X**: 매 GC actual measurement — Chrome Memory profiler.
## ❌ 안티패턴
- **Premature pool**: 매 micro-opt — measure first.
- **Pool 무제한**: 매 leak — max size cap.
- **Subarray after detach**: transferred buffer — invalid.
- **Concurrent writes without Atomics**: SharedArrayBuffer 매 race.
- **Forget to zero-fill on release**: 매 stale data leak across owners.
## 🧪 검증 / 중복
- Verified (V8 blog, MDN ArrayBuffer, WebGPU spec).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — buffer pool + view layout pattern |