0
0
Vueframework~8 mins

Virtual DOM and diffing mental model in Vue - Performance & Optimization

Choose your learning style9 modes available
Performance: Virtual DOM and diffing mental model
HIGH IMPACT
This concept affects how quickly the page updates after user interaction by minimizing direct DOM changes.
Updating UI efficiently after state changes
Vue
<template>
  <ul>
    <li v-for="item in items" :key="item">{{ item }}</li>
  </ul>
</template>

<script setup>
import { ref } from 'vue';
const items = ref(['a', 'b', 'c']);
</script>
Vue's virtual DOM compares old and new states, updating only changed items, minimizing DOM operations.
📈 Performance GainSingle reflow and repaint for changed items only
Updating UI efficiently after state changes
Vue
const list = document.getElementById('list');
list.innerHTML = '';
items.forEach(item => {
  const li = document.createElement('li');
  li.textContent = item;
  list.appendChild(li);
});
Directly manipulating the DOM by clearing and rebuilding the entire list causes many reflows and repaints.
📉 Performance CostTriggers N reflows and repaints where N is the number of items
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Direct DOM manipulation (clearing and rebuilding)Many nodes removed and addedN reflows for N itemsHigh paint cost[X] Bad
Vue virtual DOM diffing with keysOnly changed nodes updatedSingle reflow for changesLow paint cost[OK] Good
Rendering Pipeline
Vue creates a virtual DOM tree and compares it with the previous version to find differences. Only the changed parts are updated in the real DOM, reducing layout recalculations and paint operations.
JavaScript Execution
Style Calculation
Layout
Paint
Composite
⚠️ BottleneckLayout and Paint stages due to DOM updates
Core Web Vital Affected
INP
This concept affects how quickly the page updates after user interaction by minimizing direct DOM changes.
Optimization Tips
1Use virtual DOM diffing to minimize direct DOM updates.
2Always provide stable keys in lists to help efficient element reuse.
3Avoid clearing and rebuilding large DOM sections directly.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using a virtual DOM in Vue?
AIt increases the number of DOM nodes for better visuals.
BIt eliminates the need for CSS styling.
CIt reduces direct DOM updates by batching and diffing changes.
DIt disables JavaScript execution during rendering.
DevTools: Performance
How to check: Record a performance profile while triggering UI updates. Look for long tasks caused by layout and paint.
What to look for: Check if layout and paint times are minimized and if scripting time is efficient, indicating good virtual DOM usage.