Diffing: Change only what needs to change
🎯 Introduction
We have repeatedly described comparing old and new trees and updating only the differences. This process is called diffing. In this article, we will explore Snabbdom's core strategy for comparing virtual node trees. These ideas will make Vue's update mechanism easier to understand.
🧱 What is diffing?
Diffing compares old and new virtual node trees to find a minimal set of updates.
A naive approach is to compare every node in the new tree with all nodes in the old tree. General tree comparison can cost O(n³): with 1,000 nodes, that means a billion operations, which is impractical.
Snabbdom reduces this to O(n) through rules that trade a universally optimal result for efficiency:
- Compare at the same level: do not compare nodes across levels.
- Check sameVnode: first determine whether two nodes represent the same node.
- Handle content by category: choose the update logic based on the new node's content.
⚖️ Rule 1: compare at the same level
Diffing compares nodes at the same level. If a p is under a div in the old tree but under a section in the new tree, Snabbdom does not try to recognize and move it. It removes the old node and creates a new one.
Why? Moves across levels are rare in real pages, and globally identifying them is expensive. The design trades optimal handling of unusual cases for speed in everyday cases.
⚖️ Rule 2: check sameVnode
Before comparing two nodes in detail, check whether they represent the same node. The two conditions are:
function sameVnode(a, b) {
return a.sel === b.sel && a.key === b.key;
}
- Same sel: their selectors (tag, ID, and classes) match.
- Same key: neither has a key (both are
undefined), or their keys are equal.
This is why keys mattered so much in the previous article: keys directly determine whether two nodes have the same identity.
The result determines the update path:
sameVnodeis true → callpatchVnodeto compare the content in detail.sameVnodeis false → remove the old node and create a new one to replace it.
⚖️ Rule 3: patchVnode update rules
Once the nodes are identified as the same, processing enters patchVnode. Keep this premise in mind: the node exists in both trees, so the element itself stays; only its content needs to be handled.
Snabbdom handles several cases based on the new node's content:
| New node | Old node | Operation |
|---|---|---|
Has text | Any content | Set textContent to the new text |
Has children | Has children | Call updateChildren for a double-ended comparison |
Has children | Has text | Clear text, create and insert all children |
| Neither text nor children | Has children | Remove old children one by one |
| Neither text nor children | Has text | Clear text |
The last two rows may seem puzzling: if the new node is empty, why remove its children or clear its text instead of removing the node itself?
The answer is the premise above. A new node with neither text nor children means the element still exists in the new tree; it has simply become empty. For example:
// Before: a div containing two paragraphs.
h('div', [h('p', 'A'), h('p', 'B')]);
// After: the div remains, but its content is empty.
h('div');
The correct result is an empty <div></div>: keep the div and remove both p elements. Removing the div itself would leave the page missing an element required by the new tree.
When is a node actually removed? In these two cases:
sameVnodeis false: a different node takes its place in the new tree, so the old node is replaced entirely.- Old children remain after child comparison finishes: these extra nodes no longer exist in the new tree and are removed.
Also note the first row: when the new node has text, textContent replaces the previous content. This explains the rewritten li text in experiment 1 of the previous article. Without keys, old and new li nodes pass sameVnode, and their text is overwritten.
🧠 updateChildren: double-ended comparison
When both nodes have children, Snabbdom calls updateChildren. Rather than explain it only in prose, let's walk through updating [Apple, Banana, Orange] to [Apple, Orange, Banana]. All three li nodes have keys equal to their fruit names.
What is a pointer?
A pointer is a position marker. Snabbdom places two markers in each child array, pointing to the first (head) and last (tail) nodes that have not yet been processed:
Old: [Apple] [Banana] [Orange]
↑old head ↑old tail
New: [Apple] [Orange] [Banana]
↑new head ↑new tail
In each round, Snabbdom tries four comparisons in a fixed order. As soon as one matches, it processes the match, advances the pointers, and starts the next round:
| Order | Comparison | Meaning of a match | Action |
|---|---|---|---|
| ① | Old head vs new head | The start is unchanged | Update content and advance both head pointers |
| ② | Old tail vs new tail | The end is unchanged | Update content and move both tail pointers backward |
| ③ | Old head vs new tail | The old first node moved to the end | Update content and move its real element to the end |
| ④ | Old tail vs new head | The old last node moved to the start | Update content and move its real element to the start |
If none matches, consult the key-to-index map of old children. If the new head's key exists in the old array, reuse that node and move it into place; otherwise, create a new node.
Round 1: comparison ① matches
Old: [Apple] [Banana] [Orange]
↑old head ↑old tail
New: [Apple] [Orange] [Banana]
↑new head ↑new tail
Try ① first. The old head "Apple" and new head "Apple" have the same sel and key: a match! Update Apple's content (unchanged here), then advance both head pointers by one.
Round 2: comparison ③ matches
Old: [Banana] [Orange]
↑old head ↑old tail
New: [Orange] [Banana]
↑new head ↑new tail
① Old head "Banana" vs new head "Orange": no match. ② Old tail "Orange" vs new tail "Banana": no match. ③ Old head "Banana" vs new tail "Banana": a match!
A match at ③ means Banana has moved to the end. Update its content and move the existing Banana li to the end of the list. This moves the original element rather than creating one. Then advance the old head pointer and move the new tail pointer backward.
Round 3: comparison ① matches, and we are done
Old: [Orange]
↑old head (also the old tail)
New: [Orange]
↑new head (also the new tail)
Comparison ① matches, so update Orange. Both arrays are now fully processed, and comparison ends.
Reviewing the process
To change [Apple, Banana, Orange] into [Apple, Orange, Banana], Snabbdom performs just one DOM move, moving Banana's li to the end. No text is rewritten and no elements are created.
Without keys, comparison ① in round 2 would treat Banana and Orange as the same node: both have sel li and key undefined. Elements would be reused by position and two text values rewritten. Double-ended comparison combined with keys makes updates more precise.
❓ Questions and answers
Q1: How does diffing relate to browser rendering?
The differences found during diffing immediately become real DOM operations: adding, removing, or changing elements. The browser then performs layout and painting as needed. Diffing aims to minimize those DOM operations.
Q2: Why overwrite the content when the new node has text?
Text and children are mutually exclusive. If the new node contains text, the old content, whether text or child elements, is no longer needed. Replacing it all is the most direct approach.
Q3: Does every round require four comparisons?
Each round tries up to four comparisons in order. A match is processed immediately and the pointers move. The key map is checked only if none matches. There may be several comparisons, but each step is O(1).
Q4: Does Vue 3 use the same diffing algorithm?
The underlying ideas are related, including node identity checks and comparisons from both ends. Vue 3 adds optimizations such as marking dynamic nodes at compile time and using the longest increasing subsequence to reduce moves. Understanding this article will make Vue 3 easier to study.
🧪 Exercise
Without consulting reference material, use a table to work through this update: old children [A(key:a), B(key:b), C(key:c)], new children [B(key:b), C(key:c), A(key:a)]. For each round, record which comparison matches and what operation follows.
Old: A B C
New: B C A
# Write the steps here. Hint: the first round matches old head vs new tail.
🎉 You now understand the core ideas behind diffing! In the final article, we will bring the course together by building a miniature virtual DOM.
