var root = document.getElementById('ui'); var prevState = state, prevTree = [];
functionrender(state) { // Virtual DOM is really just a tree of JavaScript objects or arrays return [ ['span', {id: 'count'}, state.items.length], ['ul', {}, state.items.map(function (item) { return ['li', {}, item] })] ] }
functionupdateUI() { var vTree = render(state); var diff = vDiff(prevTree, vTree); // Just a diff on data structures, haha :) vApply(root, diff) // Apply series of patches to real DOM
prevState = deepcopy(state); prevTree = vTree; }
我们可以比较一下 innerHTML vs. Virtual DOM 的重绘性能消耗:
innerHTML: render html string O(template size) + 重新创建所有 DOM 元素 O(DOM size)
Virtual DOM: render Virtual DOM + diff O(template size) + 必要的 DOM 更新 O(DOM change)
Virtual DOM render + diff 显然比渲染 HTML 字符串要慢,但它依然是纯 JS 层面的计算,比起后面的 DOM 操作来说,依然要高效很多。