Vue3's Compilation Optimization: Dynamic Node Collection and Targeted Updates
Description
Dynamic node collection is one of the core optimization strategies in Vue3's compilation phase. Through static analysis at compile time, it marks nodes in the virtual DOM that are subject to dynamic changes (such as text, attributes, structure, etc.) and records their dynamic types. At runtime, with the help of PatchFlags (patch flags), it enables "targeted updates"—only updating the dynamic parts while avoiding full diff comparisons, thereby improving performance.
Process
-
Compile-time Analysis
Vue3's compiler, during the template compilation phase, traverses the template's AST (Abstract Syntax Tree) to identify which nodes or attributes are dynamic. For example:- Text interpolations using
{{ }} - Attributes bound with
v-bind - Dynamic structures controlled by
v-iforv-for
The compiler assigns a unique PatchFlag (e.g.,1for dynamic text,8for dynamic attributes) to each dynamic node and merges these flags into the virtual node's properties.
- Text interpolations using
-
Generating Virtual Nodes with Flags
The compiled render function generates virtual nodes carrying apatchFlagproperty. For example:// Template: <div :id="id">{{ text }}</div> const vnode = { type: 'div', props: { id: ctx.id }, children: [ctx.text], patchFlag: 9 // Binary 1 (text dynamic) | 8 (attribute dynamic) }patchFlaguses a binary bitmask to represent multiple dynamic types, facilitating efficient merging and evaluation. -
Runtime Targeted Updates
When a component updates, the renderer checks the virtual node'spatchFlag:- If
patchFlagexists, it only processes the dynamic content marked by the flag. - For example, if
patchFlag & 1is true, only the text content is updated; ifpatchFlag & 8is true, only the attributes are compared and updated. - Static nodes or subtrees are completely skipped, requiring no comparison.
- If
-
Dynamic Node Collection and Block Tree
- For nodes containing structural directives (such as
v-if,v-for), Vue3 wraps them into a "Block" node. - A Block collects all its internal dynamic child nodes (including nested Blocks) into an array (called
dynamicChildren). - During updates, the Block directly iterates over the
dynamicChildrenarray for targeted updates, eliminating the need to recursively traverse the entire tree.
- For nodes containing structural directives (such as
Summary
Dynamic node collection, through compile-time analysis and runtime flag evaluation, optimizes the traditional virtual DOM's tree-based recursive diffing into a flat dynamic array update, significantly reducing unnecessary operations. Combined with PatchFlags and the Block tree, Vue3 achieves update granularity at the node level, which is one of the key reasons for its performance advantage over Vue2.