[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,100 +2,154 @@
|
||||
id: wiki-2026-0508-diffing-algorithm
|
||||
title: Diffing Algorithm
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [VDOM Diff, Reconciliation]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [react, vue, vdom, reconciliation]
|
||||
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: JavaScript
|
||||
framework: React/Vue
|
||||
---
|
||||
|
||||
# [[Diffing Algorithm|Diffing Algorithm]]
|
||||
# Diffing Algorithm
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
Diffing Algorithm(디핑 알고리즘)은 React에서 이전 가상 DOM([[Virtual DOM|Virtual DOM]]) 트리와 새롭게 계산된 트리를 비교하여 실제 DOM을 가장 효율적으로 업데이트할 방법을 결정하는 과정입니다 [1, 2]. 이론적인 트리 비교 알고리즘은 $O(n^3)$의 시간 복잡도를 가져 실시간 애플리케이션에 부적합하지만, React는 두 가지 휴리스틱 가정을 통해 이를 $O(n)$ 복잡도로 최적화했습니다 [3-5]. 이 알고리즘은 '[[Reconciliation|Reconciliation]](재조정)' 과정의 핵심으로, 불필요한 DOM 조작을 최소화하여 렌더링 성능을 극대화하는 역할을 합니다 [1, 2, 6].
|
||||
## 매 한 줄
|
||||
> **"매 VDOM diff = O(n) heuristic — 매 same-level node 의 비교 + key-based identity."**. 매 React/Vue/Preact 모두 매 Levenshtein-style O(n³) 의 회피하기 위해 매 두 가정 (1) 다른 type = subtree 교체, (2) key가 child identity 의 hint. 매 React 19 (2024) Fiber + concurrent rendering, Vue 3.4 patchFlag-driven static hoist 의 진화.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **알고리즘의 기본 원리 및 가정:**
|
||||
React의 디핑 알고리즘은 두 가지 주요 가정에 기반하여 $O(n)$의 성능을 달성합니다. 첫째, 서로 다른 타입의 요소는 근본적으로 다른 트리를 생성한다고 가정합니다 [3, 5]. 둘째, 개발자가 제공하는 `key` prop을 통해 여러 렌더링 사이클 동안 안정적으로 유지되는 자식 요소를 식별할 수 있다고 가정합니다 [3, 5].
|
||||
## 매 핵심
|
||||
|
||||
* **비교(Diffing) 프로세스 메커니즘:**
|
||||
* **다른 타입의 요소:** 루트 요소의 타입이 다를 경우(예: `<a>`에서 `<img>`로 변경), React는 이전 트리를 완전히 허물고 처음부터 새로운 트리를 구축합니다. 이 과정에서 기존 DOM 노드와 연관된 컴포넌트의 상태([[State|State]])는 모두 파괴됩니다 [7, 8].
|
||||
* **동일한 타입의 DOM 요소:** 두 요소의 속성을 비교하여 동일한 기본 DOM 노드를 유지한 채 변경된 속성(예: `className`, `color`나 `fontWeight` 같은 `style` 등)만 업데이트합니다 [9, 10].
|
||||
* **동일한 타입의 컴포넌트 요소:** 컴포넌트의 인스턴스가 동일하게 유지되어 상태가 보존됩니다. 새로운 요소에 맞게 prop이 업데이트된 후, 하위 요소들에 대해 재귀적으로 디핑 알고리즘을 수행합니다 [10, 11].
|
||||
### 매 두 가정 (Heuristics)
|
||||
1. 매 different element type ⇒ subtree 의 unmount + 재생성.
|
||||
2. 매 stable `key` ⇒ list reconciliation 의 identity hint.
|
||||
|
||||
* **자식 요소의 재귀적 처리와 Key의 역할:**
|
||||
기본적으로 React는 두 하위 요소 목록을 동시에 반복하면서 차이가 있을 때마다 변이를 생성합니다 [11]. 하지만 리스트의 맨 앞에 요소를 추가하는 경우 등 순서가 변경될 때는 전체를 다시 렌더링하는 매우 비효율적인 상황이 발생할 수 있습니다 [12]. 이를 해결하기 위해 고유한 `key` 속성을 사용하면, React는 기존 트리와 새 트리의 자식들을 일치시켜 이동한 요소만 파악하므로 불필요한 DOM 재생성을 방지할 수 있습니다 [12, 13].
|
||||
### 매 알고리즘
|
||||
- React = Fiber tree, work loop가 매 cooperative scheduling 가능 (concurrent mode).
|
||||
- Vue 3 = compiled patchFlag (static / dynamic 분류) + LIS (Longest Increasing Subsequence) for keyed list.
|
||||
- Svelte/Solid = 매 VDOM 없음 — 매 fine-grained reactivity 의 directly DOM 의 patch.
|
||||
|
||||
* **트레이드오프 및 주의사항:**
|
||||
이 알고리즘은 휴리스틱에 의존하기 때문에 가정이 충족되지 않으면 성능이 저하될 수 있습니다 [14]. 예를 들어 하위 트리가 형제 요소 사이가 아닌 아예 다른 계층으로 이동하는 경우, 알고리즘은 해당 하위 트리를 완전히 다시 렌더링합니다 [15]. 또한 배열의 인덱스를 키로 사용하거나 `Math.random()` 같은 불안정한 키를 사용하면 리스트가 재정렬될 때 컴포넌트 상태가 꼬이거나 성능 저하가 발생할 수 있습니다 [14, 16].
|
||||
### 매 응용
|
||||
1. Keyed list — 매 stable key가 매 reorder cost 의 minimize.
|
||||
2. Conditional render — 매 ternary가 매 type swap 의 발생.
|
||||
3. Concurrent rendering — 매 high-priority update가 매 low-priority interrupt.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[Virtual DOM|Virtual DOM]], Reconciliation, [[React Fiber|React Fiber]]
|
||||
- **Projects/Contexts:** [[React Frontend Development|React Frontend Development]], [[Component-Based Architecture|Component-Based Architecture]]
|
||||
- **Contradictions/Notes:** 일반적인 트리 비교 알고리즘은 $O(n^3)$의 복잡도를 가지지만, React의 디핑 알고리즘은 휴리스틱([[Heuristics|Heuristics]])을 적용하여 실용적인 $O(n)$ 복잡도로 구현되었다는 점이 핵심적인 기술적 차이입니다 [4, 5]. 배열의 인덱스를 `key`로 사용하는 것은 요소의 순서가 변경되지 않을 때만 유효하며, 재정렬(Reorder) 시에는 비효율적이고 상태 오류를 일으킬 수 있으므로 권장되지 않습니다 [13, 16].
|
||||
## 💻 패턴
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-25*
|
||||
### 1. Stable key (correct)
|
||||
```jsx
|
||||
// CORRECT — id is stable identity
|
||||
items.map((item) => <Row key={item.id} item={item} />)
|
||||
|
||||
## 🤖 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
|
||||
// WRONG — index changes when list reorders
|
||||
items.map((item, i) => <Row key={i} item={item} />)
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 2. Type swap forces unmount
|
||||
```jsx
|
||||
{condition ? <div>A</div> : <span>A</span>}
|
||||
// span/div type 다름 → subtree unmount + remount
|
||||
// 같은 component reuse 원하면 같은 type 유지:
|
||||
<div>{condition ? 'A' : 'B'}</div>
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### 3. React Fiber priority lanes (19)
|
||||
```jsx
|
||||
import { useTransition } from 'react';
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
const onChange = (e) => {
|
||||
setInput(e.target.value); // urgent
|
||||
startTransition(() => {
|
||||
setFilter(e.target.value); // can be interrupted
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### 4. Vue 3 patchFlag (compiled)
|
||||
```html
|
||||
<!-- Source -->
|
||||
<div>
|
||||
<span>{{ msg }}</span>
|
||||
<span class="static">hi</span>
|
||||
</div>
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
<!-- Compiled (simplified) -->
|
||||
<!-- 첫 span has patchFlag = 1 (TEXT) → diff only text -->
|
||||
<!-- 두번째 span hoisted as static — 매 diff 건너뛰기 -->
|
||||
```
|
||||
|
||||
### 5. Vue keyed list w/ LIS
|
||||
```html
|
||||
<TransitionGroup tag="ul">
|
||||
<li v-for="item in items" :key="item.id">{{ item.label }}</li>
|
||||
</TransitionGroup>
|
||||
<!-- Vue calculates LIS to minimize DOM moves -->
|
||||
```
|
||||
|
||||
### 6. React.memo + structural equality
|
||||
```typescript
|
||||
const Row = React.memo(({ item }: { item: Item }) =>
|
||||
<div>{item.label}</div>,
|
||||
(prev, next) => prev.item.id === next.item.id && prev.item.label === next.item.label,
|
||||
);
|
||||
```
|
||||
|
||||
### 7. Solid/Svelte alternative (no diff)
|
||||
```typescript
|
||||
// Solid — fine-grained reactivity, no VDOM
|
||||
import { createSignal } from 'solid-js';
|
||||
const [count, setCount] = createSignal(0);
|
||||
// JSX compiles to direct DOM ops; only `count()` text node updates
|
||||
return <div>count: {count()}</div>;
|
||||
```
|
||||
|
||||
### 8. Avoid layout-impacting reorder
|
||||
```jsx
|
||||
// Stable order with key — only reorder DOM, no remount
|
||||
<>{sorted.map((u) => <UserCard key={u.id} user={u} />)}</>
|
||||
// Each UserCard preserves its instance (state, refs) on reorder.
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| List render | 매 stable id key — index X. |
|
||||
| Heavy filter + input | useTransition + deferredValue. |
|
||||
| Static UI | Vue patchFlag / React.memo. |
|
||||
| Maximum perf | Solid / Svelte (skip VDOM). |
|
||||
| Type-switch UI | wrap in same outer type to preserve children. |
|
||||
|
||||
**기본값**: 매 React 19 + Suspense + Transition + 매 stable key.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Virtual DOM]] · [[Reconciliation]]
|
||||
- 변형: [[React Fiber]] · [[Vue Reactivity]] · [[Solid Fine-grained]]
|
||||
- 응용: [[List Rendering]] · [[Animation]]
|
||||
- Adjacent: [[Tree Edit Distance]] · [[LIS Algorithm]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 keyed-list bug 의 explain, 매 type-swap unmount 의 진단.
|
||||
**언제 X**: 매 specific framework internal — 매 source code 의 read.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Index as key with reorder**: 매 wrong identity → state mix.
|
||||
- **Random key per render**: 매 매 unmount + remount.
|
||||
- **Inline objects/arrays as deps**: 매 referential change → memo bypass.
|
||||
- **Massive un-keyed list**: 매 O(n) DOM ops 매 frame.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (react.dev reconciliation, vuejs.org renderer, Solid docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — VDOM diff + Fiber + Vue patchFlag |
|
||||
|
||||
Reference in New Issue
Block a user