Skip to content
Diffing Algorithm
step 1/5

Reading — step 1 of 5

Read

~2 min readVirtual DOM & Diffing

Diffing Algorithm

When state changes, render produces a NEW vnode tree. Compare to OLD tree, apply minimal DOM changes.

python

Key insight: same-position children compared pairwise. Different = full subtree replace.

Generally O(n) where n = total nodes. NOT O(n²) tree edit distance — that would be too slow for live UIs.

Heuristic: assume parents preserve children in same positions. Wrong if children reorder; that's where keys come in.

Keys (for stable identity):

python

Diff with keys:

  • Match old and new children by key.
  • Reorder DOM nodes accordingly.
  • Skip diffing of unmoved keys.
python

Without keys: re-render of large lists is slow + can mismatch state (input value, scroll position).

React's reconciliation: O(n) by assuming local stable order; uses keys for hint.

Vue 3 uses a similar but simpler diff.

Solid + Svelte don't diff: compile-time analysis tracks exactly what changes.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…