[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,97 +2,179 @@
|
||||
id: wiki-2026-0508-batching
|
||||
title: Batching
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-723577]
|
||||
aliases: [Update Batching, Render Batching]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [batching, performance, rendering, reactive]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Batching"
|
||||
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: React/Vue/Svelte
|
||||
---
|
||||
|
||||
# [[Batching|Batching]]
|
||||
# Batching
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> Batching(배칭)은 렌더링 성능을 최적화하기 위해 여러 개의 렌더링 객체나 처리 명령을 하나의 그룹으로 묶어 일괄적으로 실행하는 기법입니다. 주로 3D 그래픽스([[WebGL|WebGL]], WebGPU) 환경에서 GPU로 보내는 드로우 콜([[Draw Call|Draw Call]]) 횟수를 줄여 성능 오버헤드를 최소화하는 데 사용됩니다. 또한 웹 개발 환경에서는 DOM의 읽기 및 쓰기 작업을 묶어 불필요한 레이아웃 재계산을 방지하는 목적으로도 활용됩니다.
|
||||
## 매 한 줄
|
||||
> **"매 여러 update 매 한 번 처리"**. Batching은 multiple state changes를 single update cycle로 묶어 redundant rendering/computation을 줄이는 reactive UI 의 core optimization. 2026 모든 mainstream framework (React, Vue, Svelte, Solid) 에서 default behavior.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **드로우 콜(Draw Call) 최소화 전략**
|
||||
성능은 종종 실행되는 명령(드로우 콜)의 수에 크게 의존하기 때문에, 여러 그리기 호출을 하나의 WebGL 호출로 병합하는 배칭 기능은 성능 향상의 핵심입니다 [1, 2].
|
||||
* **3D 그래픽스 엔진에서의 활용**
|
||||
* **[[Cesium|Cesium]]:** 여러 객체를 하나의 명령으로 결합하기 위해 배칭을 사용합니다. 예를 들어, `BillboardCollection`은 가능한 한 많은 빌보드(Billboard)를 하나의 정점 버퍼(Vertex Buffer)에 저장하고, 이를 동일한 셰이더를 통해 렌더링함으로써 명령의 수를 대폭 줄입니다 [1]. 또한 엔진이 가시 절두체(Frustum)를 분할할 때마다 명령을 개별적으로 정렬 및 배칭(Batch)하여 작동 지연 시간을 최소화합니다 [3].
|
||||
* **[[Wonder|Wonder]]land Engine:** 배칭 기능을 극한으로 적용하여, 수만 개의 동적 객체가 포함된 장면(Scene)을 자동으로 10개 미만의 드로우 콜로 렌더링해 냅니다 [2].
|
||||
* **WebGPU에서의 명령어 배칭(Command Batching)**
|
||||
WebGPU는 명령어 기록과 제출을 분리하는 구조를 가집니다. 명령들은 명령 버퍼(Command buffers)에 기록된 후, 일괄적으로(in batches) GPU 큐(Queue)에 제출됩니다 [4]. 이는 프레임당 API 오버헤드를 크게 줄여주며, GPU 드라이버가 명령어 실행을 더 효과적으로 최적화할 수 있게 만듭니다 [4].
|
||||
* **UI 레이아웃 및 DOM 성능 최적화**
|
||||
웹 성능 지표([[Core Web Vitals|Core Web Vitals]]) 중 하나인 INP(Interaction to Next Paint)를 최적화하기 위해서도 배칭 개념이 쓰입니다. 읽기 작업 직후 쓰기 작업을 수행하여 발생하는 과도한 동기식 레이아웃 재계산(레이아웃 스래싱)을 방지하기 위해, DOM 읽기 및 쓰기 작업을 현명하게 배칭(Batch)하여 처리하는 것이 권장됩니다 [5].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
|
||||
### 매 batching 이 필요한 이유
|
||||
- 매 setState 매 separate render → DOM mutation N times.
|
||||
- 매 batching → microtask/tick 까지 모아 single commit → DOM mutation 1 time.
|
||||
- Layout thrashing 방지, paint 횟수 감소.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** Draw Calls, [[WebGL|WebGL]], WebGPU, [[Interaction to Next Paint (INP)|Interaction to Next Paint (INP]]
|
||||
- **Projects/Contexts:** [[Cesium|Cesium]], [[Wonderland Engine|Wonderland Engine]]
|
||||
- **Contradictions/Notes:** 소스 내에서 배칭에 관한 상충되는 의견은 없으나, 3D 엔진에서의 '드로우 콜 병합'과 프론트엔드 최적화에서의 'DOM 연산 일괄 처리'라는 서로 다른 두 가지 시스템 컨텍스트에서 성능 개선을 위한 공통된 원리로 작용하고 있음을 보여줍니다.
|
||||
### Framework comparison
|
||||
- **React 18+**: 매 모든 context automatic.
|
||||
- **Vue 3**: nextTick scheduler — sync write, async render.
|
||||
- **Svelte 5 (runes)**: microtask flush.
|
||||
- **Solid**: `batch()` explicit + signal-based fine-grained update.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-19*
|
||||
### 매 응용
|
||||
1. Form multi-field update.
|
||||
2. Async fetch result write.
|
||||
3. Animation frame scheduling.
|
||||
|
||||
---
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 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
|
||||
### React 18+ implicit batching
|
||||
```tsx
|
||||
function update() {
|
||||
setA(1);
|
||||
setB(2);
|
||||
setC(3);
|
||||
// 매 single render
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Vue 3 batched watcher
|
||||
```ts
|
||||
import { ref, watchEffect, nextTick } from 'vue';
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const count = ref(0);
|
||||
watchEffect(() => console.log(count.value));
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
count.value++;
|
||||
count.value++;
|
||||
count.value++;
|
||||
await nextTick();
|
||||
// 매 console.log 매 한 번
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Solid explicit batch
|
||||
```tsx
|
||||
import { batch, createSignal } from 'solid-js';
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
const [a, setA] = createSignal(0);
|
||||
const [b, setB] = createSignal(0);
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
batch(() => {
|
||||
setA(1);
|
||||
setB(2);
|
||||
}); // 매 single update
|
||||
```
|
||||
|
||||
### Custom batcher (vanilla JS)
|
||||
```ts
|
||||
class Batcher {
|
||||
private queue = new Set<() => void>();
|
||||
private scheduled = false;
|
||||
|
||||
schedule(fn: () => void) {
|
||||
this.queue.add(fn);
|
||||
if (!this.scheduled) {
|
||||
this.scheduled = true;
|
||||
queueMicrotask(() => this.flush());
|
||||
}
|
||||
}
|
||||
|
||||
private flush() {
|
||||
for (const fn of this.queue) fn();
|
||||
this.queue.clear();
|
||||
this.scheduled = false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### RAF-based animation batching
|
||||
```ts
|
||||
let pending: (() => void)[] = [];
|
||||
let frameId: number | null = null;
|
||||
|
||||
function scheduleAnimation(fn: () => void) {
|
||||
pending.push(fn);
|
||||
if (frameId === null) {
|
||||
frameId = requestAnimationFrame(() => {
|
||||
const fns = pending;
|
||||
pending = [];
|
||||
frameId = null;
|
||||
for (const f of fns) f();
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Database write batching
|
||||
```ts
|
||||
class WriteBatcher {
|
||||
private buffer: Record[] = [];
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
|
||||
add(r: Record) {
|
||||
this.buffer.push(r);
|
||||
if (!this.timer) {
|
||||
this.timer = setTimeout(() => this.flush(), 50);
|
||||
}
|
||||
if (this.buffer.length >= 1000) this.flush();
|
||||
}
|
||||
|
||||
private async flush() {
|
||||
if (this.timer) { clearTimeout(this.timer); this.timer = null; }
|
||||
const batch = this.buffer.splice(0);
|
||||
if (batch.length) await db.insertMany(batch);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| React UI | Default automatic batching |
|
||||
| Solid signal | Explicit `batch()` |
|
||||
| Vanilla DOM | `queueMicrotask` 또는 RAF |
|
||||
| API write throttling | timer + size threshold |
|
||||
| Need immediate flush | `flushSync` (React) / explicit await |
|
||||
|
||||
**기본값**: framework default, only override when necessary.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Reactive Programming]] · [[Performance]]
|
||||
- 변형: [[Automatic Batching]] · [[Microtask Scheduling]]
|
||||
- 응용: [[Form State]] · [[Animation Loop]]
|
||||
- Adjacent: [[Debouncing]] · [[Throttling]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: framework batching behavior 설명, custom batcher prototyping, batching vs debouncing 구분.
|
||||
**언제 X**: real perf measurement — Profiler / Chrome DevTools.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Force flush 남용**: synchronous render 강제 → 매 batching benefit 의 lost.
|
||||
- **State variable explosion**: 5+ useState → useReducer / Object state.
|
||||
- **Async loop 안 setState**: 매 await 마다 매 separate batch — group with Promise.all.
|
||||
- **No throttle on rapid event**: scroll/resize raw — RAF / debounce.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (React 18 RFC, Vue 3 reactivity guide, Solid docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — generic batching across frameworks |
|
||||
|
||||
Reference in New Issue
Block a user