[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,105 +2,229 @@
|
||||
id: wiki-2026-0508-object-pooling-오브젝트-풀링
|
||||
title: Object Pooling (오브젝트 풀링)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-1F94B3]
|
||||
aliases: [오브젝트 풀링, Object Pool Pattern]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [pattern, performance, memory, gc, gamedev]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Object [[Pooling]] (오브젝트 풀링)"
|
||||
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: typescript
|
||||
framework: agnostic
|
||||
---
|
||||
|
||||
# [[Object Pooling (오브젝트 풀링)]]
|
||||
# Object Pooling (오브젝트 풀링)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> 오브젝트 풀링은 객체의 빈번한 생성과 파괴로 인해 발생하는 메모리 할당 비용과 가비지 컬렉션(GC) 스파이크를 방지하기 위해, 미리 고정된 개수의 객체 풀(Pool)을 할당해 두고 필요할 때 꺼내어 재사용한 뒤 다시 반환하는 소프트웨어 성능 최적화 디자인 패턴입니다.
|
||||
## 매 한 줄
|
||||
> **"매 expensive object 의 reuse 로 GC pressure + allocation cost 의 회피"**. 매 game loop / hot path / high-frequency event handler 의 standard 의 패턴 — 매 2026 의 game engine (Three.js, Bevy, Unity DOTS), DB connection pool, HTTP keep-alive, worker pool 의 universal 의 pattern.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
**1. 도입 목적과 메모리 파편화 방지** 실시간 상호작용이 중요한 게임(예: 슈팅 게임의 탄환, 파티클 시스템)에서 매 프레임마다 수백 개의 객체를 생성하고 삭제하면 시스템 자원을 소모하여 화면이 끊기는 지연(Lag) 현상이 발생합니다. 이는 가비지 컬렉터가 메모리를 정리하는 데 시간이 걸리기 때문입니다. 또한, 잦은 할당과 해제는 힙 메모리의 가용 공간을 작은 조각으로 나누어버리는 '메모리 파편화([[memory]] Fragmentation)'를 유발하여 결국 메모리 할당 실패와 크래시를 초래할 수 있습니다. 오브젝트 풀은 로딩 시점 등 초기에 큰 메모리를 한 번에 할당하고 이를 유지함으로써 이러한 문제를 원천 차단합니다.
|
||||
## 매 핵심
|
||||
|
||||
**2. 작동 원리** 오브젝트 풀은 카드의 내용을 지우고 다시 덱에 넣는 것과 같습니다.
|
||||
### 매 3-component
|
||||
- **Pool**: 매 object 의 collection (free list).
|
||||
- **Acquire**: 매 free object 의 dequeue (또는 신규 생성).
|
||||
- **Release**: 매 object 의 reset + enqueue.
|
||||
|
||||
- **사전 할당 (Pre-warming):** 초기 크기만큼 객체를 생성하여 비활성 상태로 보관합니다.
|
||||
- **활성화 및 재사용:** 객체가 필요할 때 풀에서 가용한 객체를 가져와 상태를 초기화한 뒤 활성화(In-use)합니다.
|
||||
- **반환:** 사용이 끝난 객체는 메모리에서 삭제하는 대신 비활성 상태로 변경하여 풀에 반환합니다.
|
||||
### 매 언제 적용
|
||||
- 매 allocation rate > 10K/sec.
|
||||
- 매 object lifetime 의 짧음 (< 1 frame).
|
||||
- 매 GC pause 의 user-visible (game, real-time).
|
||||
- 매 expensive constructor (DB connect, file open, GPU buffer alloc).
|
||||
|
||||
**3. 한계점 및 부작용 관리**
|
||||
### 매 응용
|
||||
1. Game particle system — bullet, explosion, enemy.
|
||||
2. DB connection pool — `pg-pool`, HikariCP.
|
||||
3. HTTP agent — `http.Agent({ keepAlive: true })`.
|
||||
4. Web Worker pool — `piscina`.
|
||||
|
||||
- **메모리 낭비와 크기 고정:** 풀의 크기가 너무 크면 사용되지 않는 객체들이 메모리를 계속 점유하여 자원을 낭비하게 되며, 반대로 너무 작으면 필요한 순간에 객체를 가져오지 못할 수 있습니다.
|
||||
- **객체 크기 고정:** 서로 다른 타입이나 크기의 객체를 하나의 풀에서 관리할 경우, 가장 큰 객체의 크기에 맞춰 슬롯 메모리를 할당해야 하므로 메모리 낭비가 발생합니다.
|
||||
- **불완전한 초기화 위험:** 재사용되는 객체는 이전 생애(Past life)의 데이터 흔적이 남아있을 수 있습니다. 객체를 풀에서 꺼낼 때 새로운 상태로 완벽하게 덮어쓰기(초기화)하지 않으면 심각한 버그가 발생할 수 있습니다.
|
||||
- **참조 유지 버그:** 풀에 반환된 객체를 다른 클래스에서 여전히 참조하고 조작할 경우, 엉뚱한 곳에서 객체가 변경되는 추적하기 힘든 버그(Use-after-free)가 발생할 수 있습니다.
|
||||
## 💻 패턴
|
||||
|
||||
**4. 고속화를 위한 Free List (프리 리스트) 기법** 가장 단순한 오브젝트 풀은 가용한 객체를 찾기 위해 풀 전체를 순회하므로 $O(n)$의 시간이 걸립니다. 이를 최적화하기 위해 비활성 상태인 객체들의 사용하지 않는 메모리 공간(예: C++의 `union`)을 활용하여 다음 빈 객체를 가리키는 포인터를 저장하는 **프리 리스트(Free List)**를 구축하면, 추가적인 메모리 낭비 없이 $O(1)$의 속도로 즉시 객체를 할당할 수 있습니다.
|
||||
### Generic pool (TypeScript)
|
||||
```typescript
|
||||
class ObjectPool<T> {
|
||||
private free: T[] = [];
|
||||
constructor(
|
||||
private factory: () => T,
|
||||
private reset: (obj: T) => void,
|
||||
initialSize = 0
|
||||
) {
|
||||
for (let i = 0; i < initialSize; i++) this.free.push(factory());
|
||||
}
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
acquire(): T {
|
||||
return this.free.pop() ?? this.factory();
|
||||
}
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[Garbage Collection]] (GC) 최적화, Generational GC (세대별 가비지 컬렉션), Memory Fragmentation (메모리 파편화), [[InstancedMesh (드로우 콜 최적화)]]
|
||||
- **Projects/Contexts:** [[대규모 파티클 시스템 최적화]], 슈팅 게임의 대규모 탄환(Bullet) 제어 시스템, React Three Fiber 엔진 아키텍처
|
||||
- **Contradictions/Notes:** 오브젝트 풀링이 모든 상황에서 정답은 아닙니다. V8과 같은 최신 자바스크립트 엔진의 세대별 가비지 컬렉터(Generational GC)는 단기 생존 객체(Short-lived objects)를 수거하는 비용이 사실상 0에 가깝습니다. 이 환경에서 객체 풀링을 잘못 적용하면, 객체들이 강제로 오래 살아남게 되어 구세대(Old Generation) 메모리를 압박하고 오히려 GC 성능을 악화시키며 메모리 사용량만 늘릴 위험이 있습니다. 반드시 프로파일러를 통한 성능 병목 확인 후 선별적으로 도입해야 합니다.
|
||||
|
||||
---
|
||||
|
||||
_Last updated: 2026-04-15_
|
||||
|
||||
---
|
||||
|
||||
## 🤖 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
|
||||
release(obj: T): void {
|
||||
this.reset(obj);
|
||||
this.free.push(obj);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Three.js Vector3 pool (game loop)
|
||||
```typescript
|
||||
import { Vector3 } from 'three';
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const vec3Pool = new ObjectPool<Vector3>(
|
||||
() => new Vector3(),
|
||||
(v) => v.set(0, 0, 0),
|
||||
256
|
||||
);
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
function updateBullet(b: Bullet, dt: number) {
|
||||
const tmp = vec3Pool.acquire();
|
||||
tmp.copy(b.velocity).multiplyScalar(dt);
|
||||
b.position.add(tmp);
|
||||
vec3Pool.release(tmp);
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Particle system pool
|
||||
```typescript
|
||||
class Particle {
|
||||
position = new Vector3();
|
||||
velocity = new Vector3();
|
||||
life = 0;
|
||||
active = false;
|
||||
}
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
class ParticleSystem {
|
||||
private pool: Particle[];
|
||||
private active: Particle[] = [];
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
constructor(maxParticles: number) {
|
||||
this.pool = Array.from({ length: maxParticles }, () => new Particle());
|
||||
}
|
||||
|
||||
spawn(pos: Vector3, vel: Vector3, life: number) {
|
||||
const p = this.pool.pop();
|
||||
if (!p) return; // pool exhausted
|
||||
p.position.copy(pos);
|
||||
p.velocity.copy(vel);
|
||||
p.life = life;
|
||||
p.active = true;
|
||||
this.active.push(p);
|
||||
}
|
||||
|
||||
update(dt: number) {
|
||||
for (let i = this.active.length - 1; i >= 0; i--) {
|
||||
const p = this.active[i];
|
||||
p.life -= dt;
|
||||
if (p.life <= 0) {
|
||||
p.active = false;
|
||||
this.active.splice(i, 1);
|
||||
this.pool.push(p); // return to pool
|
||||
} else {
|
||||
p.position.addScaledVector(p.velocity, dt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### DB connection pool (pg)
|
||||
```typescript
|
||||
import { Pool } from 'pg';
|
||||
|
||||
const pool = new Pool({
|
||||
max: 20,
|
||||
idleTimeoutMillis: 30_000,
|
||||
connectionTimeoutMillis: 2000,
|
||||
});
|
||||
|
||||
async function query(sql: string, params: unknown[]) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
return await client.query(sql, params);
|
||||
} finally {
|
||||
client.release(); // ← back to pool
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Worker thread pool (piscina)
|
||||
```typescript
|
||||
import Piscina from 'piscina';
|
||||
|
||||
const piscina = new Piscina({
|
||||
filename: new URL('./worker.js', import.meta.url).href,
|
||||
minThreads: 2,
|
||||
maxThreads: 8,
|
||||
});
|
||||
|
||||
const result = await piscina.run({ payload: data });
|
||||
```
|
||||
|
||||
### Bounded pool with backpressure
|
||||
```typescript
|
||||
class BoundedPool<T> {
|
||||
private free: T[] = [];
|
||||
private waiters: ((obj: T) => void)[] = [];
|
||||
private created = 0;
|
||||
|
||||
constructor(
|
||||
private factory: () => T,
|
||||
private reset: (obj: T) => void,
|
||||
private max: number
|
||||
) {}
|
||||
|
||||
async acquire(): Promise<T> {
|
||||
if (this.free.length) return this.free.pop()!;
|
||||
if (this.created < this.max) {
|
||||
this.created++;
|
||||
return this.factory();
|
||||
}
|
||||
return new Promise((resolve) => this.waiters.push(resolve));
|
||||
}
|
||||
|
||||
release(obj: T): void {
|
||||
this.reset(obj);
|
||||
const w = this.waiters.shift();
|
||||
if (w) w(obj);
|
||||
else this.free.push(obj);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Hot path allocation (game loop) | object pool (generic) |
|
||||
| DB / network connection | bounded pool with backpressure |
|
||||
| Heavy CPU task | worker thread pool (piscina) |
|
||||
| Short-lived simple obj (< 1KB) | 매 V8 의 young-gen GC 의 충분 — pool 의 X |
|
||||
| Object 의 reset cost > construct cost | pool 의 X |
|
||||
|
||||
**기본값**: 매 profile 후 의 적용 — premature pooling 의 X.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Garbage Collection]] · [[V8 엔진 힙 아키텍처]]
|
||||
- 변형: [[bitECS와 SharedArrayBuffer를 결합한 멀티스레드 고성능 아키텍처]]
|
||||
- 응용: [[InstancedMesh 최적화]] · [[가변적 LOD(Level of Detail) 시스템]]
|
||||
- Adjacent: [[Old Space]] · [[세대 가설(Generational Hypothesis)]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: game loop / real-time pipeline 의 GC pause 회피, expensive resource (DB conn, GPU buffer) 의 reuse.
|
||||
**언제 X**: simple short-lived object — 매 modern GC 의 충분.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Reset 의 누락**: 매 stale state 의 leak — 매 security risk (sensitive data).
|
||||
- **Unbounded pool**: 매 memory leak — 매 max size 의 강제.
|
||||
- **Pool 의 lock contention**: 매 multi-thread 의 sync overhead — thread-local pool 의 고려.
|
||||
- **Object 의 over-aliasing**: 매 release 후 의 reference 유지 — use-after-free 의 bug.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Game Programming Patterns / R. Nystrom, V8 blog, piscina docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — TS generic pool, Three.js, piscina 패턴 추가 |
|
||||
|
||||
Reference in New Issue
Block a user