Files
2nd/10_Wiki/Topics/Frontend/JavaScript-Optimization-Patterns.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

226 lines
6.7 KiB
Markdown

---
id: wiki-2026-0508-javascript-optimization-patterns
title: JavaScript Optimization Patterns
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [JS Performance Patterns, V8 Optimization, JS Hot Path]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [javascript, performance, v8, optimization]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: javascript
framework: v8
---
# JavaScript Optimization Patterns
## 매 한 줄
> **"매 hot path 의 type stability + allocation 최소화"**. V8/JSC/SpiderMonkey 모두 매 inline cache + hidden class 의 의존 — 매 monomorphic call site 가 매 fastest. 매 micro-optimization 보다 매 algorithmic / batching 이 매 win 큼, 매 그러나 hot loop 에서는 매 GC pressure 의 의식 필수.
## 매 핵심
### 매 V8 의 fast path
- **Hidden class (Map)**: object shape — 매 동일 property 순서 의 같은 hidden class.
- **Inline cache (IC)**: call site 별 type 기록 — monomorphic > polymorphic > megamorphic.
- **TurboFan / Maglev**: hot function 의 optimizing compile, type feedback 기반.
- **Sparkplug** (2021+): 매 baseline JIT, 매 quick startup.
### 매 GC pressure
- **Young generation (Scavenger)**: 매 short-lived alloc — 매 cheap.
- **Old generation (Mark-Compact)**: 매 promoted object — 매 stop-the-world 의 risk.
- **Strategy**: 매 hot loop 에서 alloc 의 회피 (object pooling, typed arrays).
### 매 응용
1. Animation / game loop 의 60+ FPS 유지.
2. 매 large data transformation (millions of records).
3. Server-side hot path (Node, Bun).
## 💻 패턴
### Object shape stability
```javascript
// X — hidden class 가 다름 (assignment 순서)
function A() { this.x = 1; this.y = 2; }
function B() { this.y = 2; this.x = 1; }
const arr = [new A(), new B()]; // 매 polymorphic IC
// O — 매 동일 shape
class Point { constructor(x, y) { this.x = x; this.y = y; } }
const arr2 = [new Point(1, 2), new Point(3, 4)];
```
### Monomorphic call site
```javascript
function add(a, b) { return a + b; } // V8 의 type feedback 기록
// X — megamorphic (string + number + array)
add(1, 2); add('a', 'b'); add([], []);
// O — monomorphic (always number)
for (let i = 0; i < 1e6; i++) add(i, i + 1);
```
### Typed arrays (no boxing)
```javascript
// X — 매 Array of number — boxed double, GC pressure
const heights = new Array(1_000_000);
for (let i = 0; i < heights.length; i++) heights[i] = Math.random();
// O — Float64Array — flat, no boxing
const heights2 = new Float64Array(1_000_000);
for (let i = 0; i < heights2.length; i++) heights2[i] = Math.random();
```
### Object pooling (hot loop)
```javascript
class Vec3Pool {
#pool = [];
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) { this.#pool.push(v); }
}
const pool = new Vec3Pool();
function frame() {
const tmp = pool.acquire(1, 2, 3);
// ... compute ...
pool.release(tmp);
}
```
### Loop hoisting
```javascript
// X — length 매 iter 마다 access
for (let i = 0; i < items.length; i++) { ... }
// O — modern V8 의 자동 hoist 하지만 매 explicit 가 안전
const n = items.length;
for (let i = 0; i < n; i++) { ... }
// O+ — for-of with iterator (매 modern, V8 fast path)
for (const it of items) { ... }
```
### Map vs object lookup
```javascript
// 매 string key 의 dynamic — Map 의 매 fast & predictable
const cache = new Map();
cache.set(key, value);
cache.get(key);
// 매 known small fixed keys — object 매 inline cache 의 winning
const config = { mode: 'fast', retries: 3 };
```
### Avoid `arguments`, use rest
```javascript
// X — arguments 의 deopt (non-array, function-bound)
function sum() {
let s = 0;
for (let i = 0; i < arguments.length; i++) s += arguments[i];
return s;
}
// O
function sum(...nums) {
let s = 0;
for (const n of nums) s += n;
return s;
}
```
### Batching DOM / state updates
```javascript
// X — 매 update 의 layout thrash
items.forEach(it => container.appendChild(make(it)));
// O — DocumentFragment batch
const frag = document.createDocumentFragment();
items.forEach(it => frag.appendChild(make(it)));
container.appendChild(frag);
```
### Web Workers (off-main-thread)
```javascript
// main.js
const worker = new Worker('worker.js', { type: 'module' });
worker.postMessage({ data: bigArray }, [bigArray.buffer]); // 매 transfer, zero-copy
// worker.js
self.onmessage = (e) => {
const result = heavy(e.data.data);
self.postMessage(result);
};
```
### Structured cloning vs transferable
```javascript
// 매 1MB+ data — transferable 의 50-100x faster
const buf = new ArrayBuffer(1_000_000);
worker.postMessage(buf, [buf]); // 매 ownership transfer
```
### Lazy evaluation (generator)
```javascript
function* range(from, to) {
for (let i = from; i < to; i++) yield i;
}
function* map(it, f) { for (const v of it) yield f(v); }
function* filter(it, p) { for (const v of it) if (p(v)) yield v; }
// 매 1B element 의 first 10 — alloc 의 X
const result = [];
for (const v of filter(map(range(0, 1e9), x => x * 2), x => x % 3 === 0)) {
result.push(v);
if (result.length === 10) break;
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Hot loop alloc | typed array + object pool |
| Large data transform | streaming / generator |
| Heavy compute | Web Worker + transferable |
| DOM batch | DocumentFragment / requestAnimationFrame |
| Type stability 의심 | DevTools Profiler "ICs" tab |
| 매 micro-bench 결과 의 의심 | always profile in production-like build |
**기본값**: 매 algorithmic win 우선, 매 hot path 만 micro-optimize.
## 🔗 Graph
- 부모: [[JavaScript]] · [[V8]]
- 변형: [[JSC]]
- 응용: [[Web Worker (웹 워커)|Web-Workers]] · [[Animation-Performance]]
- Adjacent: [[Garbage-Collection]]
## 🤖 LLM 활용
**언제**: 매 measurable bottleneck 진단 후, hot loop 작성, large data transform.
**언제 X**: 매 cold path / one-shot script (premature optimization), 매 readability cost > perf gain.
## ❌ 안티패턴
- **Premature micro-opt**: 매 readability 희생, 매 measure 없이 추측.
- **`delete obj.prop`**: hidden class transition 유발, IC deopt.
- **Hot loop 의 closure alloc**: `arr.map(x => x*2)` 매 frame — 매 함수 hoist.
- **`try/catch` in hot loop**: 매 V8 의 optimization 일부 비활성 (개선되었지만 여전히 cost).
- **string concat in loop**: `+=` 매 hot loop — 매 array.join.
## 🧪 검증 / 중복
- Verified (V8 blog, Chrome DevTools Performance docs, Bun benchmark methodology).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — V8 hot-path optimization 패턴 정리 |