What is Vue's compiler and how does it optimize templates?
Answer
Vue 3's template compiler converts HTML-like templates into optimized JavaScript render functions. Key optimizations: 1. Static Hoisting: elements with no dynamic bindings are identified at compile time and hoisted outside the render function as module-level constants — created once per app, not every render: const _hoisted_1 = createVNode("h1", null, "Static Title"). The render function just references _hoisted_1. 2. Patch Flags: dynamic nodes get a numeric flag indicating WHAT can change. The runtime only checks flagged properties: FLAG = 2 (class is dynamic), 4 (style is dynamic), 8 (specific props), 1 (text content). Compound: 9 = class + text. Runtime uses bitwise AND to check: if (vnode.patchFlag & 8) { /* update props */ }. Only flagged parts are diffed. 3. Block Tree: the compiler creates "block" nodes for structural elements (divs, sections). A block tracks its own dynamic descendant nodes in a flat array. Diffing is O(number of dynamic nodes) instead of O(total nodes). Static subtrees inside a block are never diffed. 4. Method/handler caching: inline event handlers are cached: @click="() => foo()" compiles to a cached function — same reference each render. 5. v-once compilation: marked nodes compile to a static creation with no re-rendering code. Impact: these compile-time optimizations mean Vue 3's runtime diffing operates on far fewer nodes than React's fiber reconciler (which has no compile-time information). Vue 3 is 1.3-2x faster than Vue 2 and comparable to the fastest virtual DOM implementations.
Previous
How does Vue 3's Proxy-based reactivity system work internally?
Next
How does Vue handle SSR hydration?