Files
2nd/10_Wiki/Topics/Domain_Programming/Frontend/JavaScript-Optimization-Patterns.md
T
Antigravity Agent c24165b8bc refactor(topics): 멀티 에이전트용 지식 재편 — _Common(공통 기본기) + Domain_* 구조
에이전트 8종(대화형/프로그래머 C·S/디자이너/설계자/기획자/QA/PD/PM)에게
[공통 기본 능력 + 롤별 Specialty] 2층으로 지식을 주입하기 위한 재분류.
문서 내용·포맷은 무수정, 폴더 이동만 (6,372개 문서 수 보존 확인).

- Topic_Programming → Domain_Programming (내부 구조 보존)
- Topic_Graphic → Domain_Design
- Topic_Business → Domain_Product
- Topic_General → Domain_General
- _Common 신설: Math(구 Topic_Math_Specialty), Reasoning(구 General/From_Thinking & Reasoning),
  Reasoning_Creativity(구 General/From_창의성), Communication(Poetic_Blog_Writing + From_writing)
- 타 도메인의 From_* 폴더는 유지 (출처 표기일 뿐, 이미 도메인에 맞게 분류된 문서)
- 빈 폴더 정리 (memory/procedures)
- 에이전트→폴더 매핑은 workspace의 .astra/agent-knowledge-map.json (9개 에이전트)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 11:05:56 +09:00

6.7 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-javascript-optimization-patterns JavaScript Optimization Patterns 10_Wiki/Topics verified self
JS Performance Patterns
V8 Optimization
JS Hot Path
none A 0.9 applied
javascript
performance
v8
optimization
2026-05-10 pending
language framework
javascript 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

// 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

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)

// 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)

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

// 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

// 매 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

// 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

// 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)

// 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

// 매 1MB+ data — transferable 의 50-100x faster
const buf = new ArrayBuffer(1_000_000);
worker.postMessage(buf, [buf]); // 매 ownership transfer

Lazy evaluation (generator)

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

🤖 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 패턴 정리