Diffing: Change only what needs to change

Understand Snabbdom's diffing strategy, including same-level comparisons, sameVnode, patchVnode, and double-ended pointers.

🎯 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:

  1. Compare at the same level: do not compare nodes across levels.
  2. Check sameVnode: first determine whether two nodes represent the same node.
  3. 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:

  • sameVnode is true → call patchVnode to compare the content in detail.
  • sameVnode is 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 nodeOld nodeOperation
Has textAny contentSet textContent to the new text
Has childrenHas childrenCall updateChildren for a double-ended comparison
Has childrenHas textClear text, create and insert all children
Neither text nor childrenHas childrenRemove old children one by one
Neither text nor childrenHas textClear 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:

main.js
// 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:

  • sameVnode is 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:

OrderComparisonMeaning of a matchAction
①Old head vs new headThe start is unchangedUpdate content and advance both head pointers
②Old tail vs new tailThe end is unchangedUpdate content and move both tail pointers backward
③Old head vs new tailThe old first node moved to the endUpdate content and move its real element to the end
④Old tail vs new headThe old last node moved to the startUpdate 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.

Focus on understanding the idea rather than memorizing the steps. Remember: add keys and keep sel stable to help diffing take the most efficient path.

❓ 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.