[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
@@ -2,98 +2,188 @@
id: wiki-2026-0508-브라우저-메인-스레드-최적화-및-타임-슬라이싱
title: 브라우저 메인 스레드 최적화 및 타임 슬라이싱
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Main Thread Optimization, Time Slicing, INP Optimization, Long Tasks, Scheduler API]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [web-performance, main-thread, scheduler, inp, long-tasks, web-workers]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: vanilla-web-platform
---
# [[브라우저 메인 스레드 최적화 및 타임 슬라이싱|브라우저 메인 스레드 최적화 및 타임 슬라이싱]]
# 브라우저 메인 스레드 최적화 및 타임 슬라이싱
## 📌 한 줄 통찰 (The Karpathy Summary)
브라우저 메인 스레드 최적화 및 타임 슬라이싱은 단일 스레드로 동작하는 브라우저의 특성상 발생할 수 있는 UI 멈춤(Jank) 현상을 방지하고 상호작용성을 높이기 위한 아키텍처 접근 방식입니다 [1, 2]. 거대한 렌더링 작업을 중단 불가능한 하나의 동기적 작업으로 처리하는 대신, 타임 슬라이싱을 통해 작업을 작은 청크(단위)로 분할합니다 [1, 3]. 이를 통해 메인 스레드는 무거운 렌더링 작업을 중간에 일시 중지하고 사용자 입력과 같은 긴급한 고우선순위 작업을 먼저 처리한 후 남은 렌더링을 재개할 수 있어 애플리케이션의 반응성을 극대화합니다 [1, 4, 5].
## 한 줄
> **"매 long task 를 매 50ms 미만 chunk 로 split, scheduler.yield() 로 매 input 에 양보"**. 매 INP (Interaction to Next Paint, 2024 부터 Core Web Vital) 의 핵심 metric — 매 200ms 이하 가 Good. 매 2026 의 Scheduler API + isInputPending + Web Worker 의 매 standard toolkit.
## 📖 구조화된 지식 (Synthesized Content)
- **메인 스레드의 한계와 동기적 블로킹 문제:**
브라우저는 기본적으로 단일 스레드(Single-threaded) 환경에서 작동하며, 한 번에 하나의 태스크를 처음부터 끝까지 실행합니다 [2]. 메인 스레드는 HTML/CSS 파싱, 자바스크립트 실행, 스타일 계산, 레이아웃(Reflow) 및 페인트(Paint) 등의 렌더링 파이프라인을 모두 책임집니다 [6, 7]. 부드러운 스크롤과 상호작용을 유지하려면 16.67ms(60 FPS) 이내에 프레임 렌더링을 완료해야 합니다 [1, 7]. 그러나 대규모 컴포넌트 트리 업데이트를 단일 재귀 호출로 처리하면 이 프레임 예산을 초과하여 메인 스레드를 오랫동안 점유하게 되며, 이는 TTI(Time to Interactive)를 늦추고 브라우저가 사용자 입력에 반응하지 못하게 만듭니다 [1, 8, 9].
## 매 핵심
- **타임 슬라이싱([[Time-Slicing|Time-Slicing]])과 Fiber 아키텍처:**
이러한 메인 스레드 블로킹 문제를 해결하기 위해 React는 렌더링 작업을 작은 '작업 단위(Units of Work)'로 나누는 Fiber 아키텍처를 도입했습니다 [1, 10]. 타임 슬라이싱은 무거운 업데이트 작업을 작은 청크로 쪼개는 기법입니다 [3]. 작업 루프(Work loop)는 각 작업 단위를 처리한 후 브라우저에 남은 여유 시간이 있는지, 또는 사용자 입력과 같은 긴급한 작업이 들어왔는지 확인합니다 [4]. 만약 시간이 부족하면 렌더링 작업을 일시 중지하고 메인 스레드의 제어권을 브라우저에게 양보(Yield)합니다 [4, 11].
### 매 Main thread 의 책임
- **JS execution**, Style + Layout + Paint, Compositing prep, Event dispatch.
- **Long task**: 50ms 초과 task — INP 의 적.
- **Render-blocking**: long task 동안 rAF, input handler 모두 starve.
- **스케줄링과 우선순위(Lanes) 제어:**
스케줄러는 UI 업데이트의 우선순위를 지능적으로 관리하는 역할을 합니다 [3]. 사용자 입력(클릭, 타이핑)과 같은 작업은 가장 높은 우선순위(Sync Lane)에 할당되어 즉시 처리되며, 백그라운드 데이터 처리나 무거운 리스트 필터링 등은 낮은 우선순위로 밀려납니다 [12-14]. 스케줄러는 메인 스레드가 바쁘거나 더 높은 우선순위의 작업이 도착하면 현재 진행 중인 작업(WIP Fiber)을 일시 중지(Pause)시키고, 메인 스레드가 유휴 상태가 되었을 때 중단된 지점부터 다시 재개(Resume)합니다 [5]. 이 과정에서 `requestIdleCallback`과 같은 브라우저 API를 활용하여 UI가 멈추지 않도록 방지합니다 [11].
### 매 Time slicing 전략
- **Yield to event loop**: scheduler.yield() (2026 baseline), 매 fallback 으로 setTimeout(0).
- **Priority-aware scheduling**: scheduler.postTask({priority: 'background'}).
- **isInputPending()**: input 의 pending 시 매 즉시 yield.
- **Web Worker offload**: pure compute (parsing, encoding, crypto) 는 main thread 떠남.
- **최적화 지표 및 동시성 렌더링([[Concurrent Rendering|Concurrent Rendering]]):**
이러한 타임 슬라이싱과 우선순위 제어를 바탕으로 [[React 19|React 19]]의 `useTransition``[[useDeferredValue|useDeferredValue]]`와 같은 동시성 기능이 작동합니다 [15, 16]. 이 기능들은 무거운 연산을 비긴급 업데이트로 분류하여 메인 스레드가 사용자 입력에 즉각적으로 반응할 수 있는 공간을 확보해 줍니다 [15, 17]. 이는 자바스크립트 실행 속도 자체를 물리적으로 높이는 것은 아니지만, 긴급한 사용자 피드백이 지연되지 않게 하여 앱이 "더 빠르게 느껴지도록(Feel faster)" 인지적 성능을 크게 향상시키며, 결과적으로 INP(Interaction to Next Paint) 코어 웹 바이탈 지표를 직접적으로 개선합니다 [17, 18].
### 매 응용
1. **Large list rendering**: virtualized + chunked.
2. **JSON parsing / encoding**: Worker + Transferable.
3. **Hydration**: priority-based React 19 / Astro / Qwik resumability.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[React Fiber Architecture|React Fiber Architecture]], Concurrent Rendering, [[Critical Rendering Path|Critical Rendering Path]]
- **Projects/Contexts:** [[React 18|React 18]]/19, [[Core Web Vitals|Core Web Vitals]] (INP, TTI)
- **Contradictions/Notes:** 과거 React의 스택 리컨실러(Stack Reconciler)는 렌더링 작업이 한 번 시작되면 트리를 끝까지 동기적으로 순회해야 했기 때문에 메인 스레드를 블로킹하는 치명적 단점이 있었으나, Fiber 도입 이후 이를 중단 및 재개 가능한(Interruptible) 렌더링 모델로 개선했다는 사실이 소스 전반에 걸쳐 강조됩니다 [1, 19, 20]. 타임 슬라이싱은 코드 자체를 빠르게 만드는 것이 아니라 메인 스레드 가용성을 확보하여 체감 성능을 향상시키는 구조적 접근임을 유의해야 합니다 [18].
## 💻 패턴
---
*Last updated: 2026-04-25*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### scheduler.yield() (2026 baseline)
```typescript
async function processChunks(items: Item[]) {
for (const it of items) {
process(it);
if (navigator.scheduling?.isInputPending?.()) {
await scheduler.yield(); // resume after input is handled
}
}
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### scheduler.postTask with priority
```typescript
// User-blocking: must run ASAP
scheduler.postTask(updateUserCriticalUI, { priority: 'user-blocking' });
// User-visible: default
scheduler.postTask(refreshSidebar, { priority: 'user-visible' });
// Background: prefetch, analytics flush
scheduler.postTask(prefetchNext, { priority: 'background' });
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Manual time slicer (fallback)
```typescript
async function timeSlice<T>(items: T[], work: (item: T) => void, budgetMs = 5) {
let start = performance.now();
for (const it of items) {
work(it);
if (performance.now() - start > budgetMs) {
await new Promise<void>((r) => setTimeout(r, 0));
start = performance.now();
}
}
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Web Worker offload (Comlink pattern)
```typescript
// worker.ts
import * as Comlink from 'comlink';
const api = {
parseLargeJSON: (text: string) => JSON.parse(text),
hashFile: async (buf: ArrayBuffer) => {
const h = await crypto.subtle.digest('SHA-256', buf);
return new Uint8Array(h);
},
};
Comlink.expose(api);
**기본값:**
> *(TODO)*
// main.ts
const worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' });
const api = Comlink.wrap<typeof api>(worker);
const parsed = await api.parseLargeJSON(hugeText);
```
## ❌ 안티패턴 (Anti-Patterns)
### Transferable ArrayBuffer (zero-copy)
```typescript
const buf = new ArrayBuffer(1024 * 1024 * 10);
worker.postMessage({ buf }, [buf]); // ownership transfers; main no longer holds
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### INP measurement (Performance Observer)
```typescript
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries() as PerformanceEventTiming[]) {
const inp = entry.processingEnd - entry.startTime;
if (inp > 200) console.warn('Slow interaction', entry.name, inp);
}
});
observer.observe({ type: 'event', buffered: true, durationThreshold: 16 });
```
### React 19 — useTransition for non-urgent updates
```typescript
const [isPending, startTransition] = useTransition();
function handleSearch(q: string) {
setQuery(q); // urgent — input echo
startTransition(() => {
setSearchResults(filterHugeList(allItems, q)); // non-urgent — yields to input
});
}
```
### IntersectionObserver — lazy heavy work
```typescript
const io = new IntersectionObserver((entries) => {
for (const e of entries) {
if (e.isIntersecting) {
scheduler.postTask(() => mountHeavyComponent(e.target), { priority: 'background' });
io.unobserve(e.target);
}
}
}, { rootMargin: '200px' });
document.querySelectorAll('.lazy-section').forEach(el => io.observe(el));
```
### Long Animation Frames (LoAF) API
```typescript
new PerformanceObserver((list) => {
for (const e of list.getEntries() as any[]) {
console.warn('LoAF', e.duration, e.scripts);
}
}).observe({ type: 'long-animation-frame', buffered: true });
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| > 50ms synchronous work | Time slice with scheduler.yield() |
| Pure compute (parse, hash, image) | Web Worker + Transferable |
| Non-urgent state update (React) | useTransition |
| Off-screen heavy work | IntersectionObserver + postTask |
| Background prefetch | scheduler.postTask priority 'background' |
| Hot UI update with input | isInputPending checkpoint |
**기본값**: 매 task > 5ms 면 yield consider. 매 task > 50ms 면 split mandatory. 매 pure compute 는 Worker 의 first choice.
## 🔗 Graph
- 부모: [[Web-Performance]] · [[Core-Web-Vitals]] · [[INP-Optimization]]
- 변형: [[Scheduler-API]] · [[Web-Workers]] · [[OffscreenCanvas]]
- 응용: [[성능 중심의 웹 애니메이션 및 인터랙션 구현]] · [[Virtualized-Lists]] · [[React-Concurrent-Features]]
- Adjacent: [[Long-Tasks-API]] · [[Long-Animation-Frames]] · [[Comlink]]
## 🤖 LLM 활용
**언제**: time-slice boilerplate, Worker setup scaffold, scheduler API migration plan.
**언제 X**: 매 actual INP 측정 — RUM (CrUX, Web Vitals JS) 만 truth. LLM 의 perf claim 의 hallucination.
## ❌ 안티패턴
- **Sync heavy work in input handler**: 매 INP 폭증.
- **setTimeout(0) busy-loop**: scheduler.yield() preferred (priority-aware).
- **Worker per task spawn**: 매 startup overhead. Pool 또는 long-lived worker.
- **structuredClone of huge data to Worker**: Transferable 사용.
- **Ignoring isInputPending**: 매 yield 의 timing 의 너무 늦음.
## 🧪 검증 / 중복
- Verified (web.dev/inp 2026, Scheduler API spec, LoAF spec, Chrome DevTools Performance docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Scheduler API, time slicing, Worker offload, INP patterns |