preface

Vue.js 2.0 introduces Virtual DOM, which is 2-4 times faster than vue.js 1.0 in initial rendering and greatly reduces memory consumption. So, what is the Virtual DOM? Why the Virtual DOM? How does it improve page rendering efficiency? This is the question to be discussed in this paper.

The process of converting a template to a view

Before introducing Virtual Dom formally, it is necessary to take a look at the process of converting a template into a view, as shown below (see Vue.js) :

  • Vue. Js converts the template template into the render function by compilation, which is executed to obtain a virtual node tree
  • When the Model is operated on, the Watcher object in the corresponding Dep is fired. The Watcher object calls the corresponding UPDATE to modify the view. This process involves comparing the old and new virtual nodes and then DOM manipulation to update the view based on the comparison results.

In a nutshell, the underlying implementation of Vue compiles templates into virtual DOM rendering functions. Combined with Vue’s built-in response system, Vue can intelligently calculate the minimum cost of re-rendering components in the event of a state change and apply it to DOM operations.

  • Render functions: Render functions are used to generate the Virtual DOM. Vue recommends using templates to build our application interface. In the underlying implementation, Vue compiles templates into rendering functions, but we can also write rendering functions instead of templates for better control.
  • VNode virtual node: This can represent a real DOM node. A VNode can be rendered as a DOM node using the createElement method. Simply put, a VNode can be understood as a node description object, which describes how real DOM nodes should be created.
  • Patch (also known as patching algorithm) : The most core part of virtual DOM, it can render VNodes into real DOM. This process is to compare the differences between the old and new virtual nodes, and then find the nodes that need to be updated according to the comparison results. As can be seen from the meaning of the word, patch itself means patch and repair. Its actual function is to modify the existing DOM to realize the purpose of updating the view. Vue’s Virtual DOM Patching algorithm is based on the implementation of Snabbdom, and has made a lot of adjustments and improvements on these basis.

What is the Virtual DOM?

Virtual DOM is basically a tree based on JavaScript objects (vNodes), which are described by object attributes. In fact, it is just a layer of abstraction from the real DOM. Eventually, the tree can be mapped to the real world through a series of operations.

To put it simply, the Virtual DOM can be understood as a simple JS object, and it contains at least three attributes: tag, attrs and children. Different frameworks name these three attributes a little differently.

For virtual DOM, let’s take a look at a simple example, as shown in the figure below, which illustrates the process of template → rendering function → virtual DOM tree → real DOM in detail

What does the Virtual DOM do?

The ultimate goal of the virtual DOM is to render virtual nodes onto the view. However, if you overwrite the old node directly with the virtual node, there will be a lot of unnecessary DOM manipulation. For example, if there are many LI labels under one UL label and only one LI changes, the new UL will be used to replace the old UL, resulting in a waste of performance due to unnecessary DOM operations.

In order to avoid unnecessary DOM operations, the virtual DOM compares the virtual node with the old virtual node (oldVnode) used in the last rendering of the view during the mapping of the virtual node to the view to find the node that really needs to be updated for DOM operations, so as to avoid the operation of other DOM that need no change.

The virtual DOM does two things in vue.js:

  • Virtual nodes corresponding to real DOM nodes are provided
  • Compare the virtual node VNode with the old virtual node oldVnode and update the view

Why the Virtual DOM?

  • Have the advantage of cross-platform

Because Virtual DOM is based on JavaScript objects and does not depend on the real platform environment, it has the ability to cross platform, such as browser platform, Weex, Node, etc.

  • It is slow to operate DOM and efficient to run JS. We can put DOM comparison operations in the JS layer to improve efficiency.

Because the execution speed of DOM operations is not nearly as fast as that of Javascript, a large number of DOM operations are moved to Javascript and patching algorithm is used to calculate the nodes that really need to be updated to minimize DOM operations and significantly improve performance.

The Virtual DOM is essentially a cache between JS and DOM. The analogy is CPU and hard disk, since the hard disk is so slow, we put a cache between them: since DOM is so slow, we put a cache between them, JS and DOM. The CPU (JS) only operates on the Virtual DOM, and at the last moment writes changes to the hard disk (DOM).

  • Improved rendering performance

The advantage of Virtual DOM is not in a single operation, but in a large number of frequent data updates, the view can be reasonably and efficiently updated.

In order to realize efficient DOM operation, it is necessary to have a set of efficient virtual DOM diff algorithm. Through —-diff algorithm, the core of patch, we find out the nodes that need to be updated in DOM this time and do not update the others. What is the implementation process of the DIff algorithm?

The diff algorithm

The DIff algorithm of Vue is modified based on SNabbDOM. It only diff between vnodes of the same level, recursively diff of vnodes of the same level, and finally realize the update of the whole DOM tree. Because the number of operations across the hierarchy is so small that it is ignored, the time complexity changes from O(n3) to O(n).

The DIff algorithm consists of several steps:

  • Using JavaScript object structure to represent the DOM tree structure; Then use this tree to build a real DOM tree and plug it into the document
  • When the state changes, a new object tree is rebuilt. Then compare the new tree with the old tree and note the differences between the two trees
  • The view is updated when the recorded differences are applied to the actual DOM tree being built

Diff algorithm implementation process

The DIff algorithm itself is very complex and difficult to implement. In this paper, the following two core functions are briefly introduced:

  • Patch (container,vnode) : Render the Virtual Dom into a real Dom and insert it into the container for the first time.
  • Patch (vnode,newVnode): when rendering again, compare the newVnode to the old vnode, and then apply the difference to the real DOM tree being built.

1.patch(container,vnode)

This function allows VNode to render into a real DOM. To get a sense of the process, we can use the following simulation code:

function createElement(vnode) {    
var tag = vnode.tag  
var attrs = vnode.attrs || {}    
var children = vnode.children || []    
if(! tag) {returnVar elem = document.createElement(tag) // attribute var attrNamefor (attrName in attrs) {    
    if(attrs.hasownProperty (attrName)) {// Add elem. SetAttribute (attrName, Attrs [attrName])}} // children.function(childVnode) {// Add child elements to elem, and recursively generate child nodes if there are any. Elem. AppendChild (createElement(childVnode)) // Recursive}) // Returns the real DOM elementreturn elem
}
Copy the code

2.patch(vnode,newVnode)

Here we only consider how vnode compares to newVnode:

functionupdateChildren(vnode, NewVnode) {var children = vnode. Children | | [] var newChildren = newVnode. Children | | [] / / traverse the existing children children.forEach(function(childVnode, index) {var newChildVnode = newChildren[index] // Both tags are the sameif(childvNode. tag === newChildvNode. tag) {// Further contrast, recursive updateChildren(childVnode, newChildVnode)}elseReplaceNode (childVnode, newChildVnode)}}Copy the code

To recommend a good BUG monitoring toolFundebug, welcome free trial!

Welcome to pay attention to the public number: front-end craftsmen, we will witness your growth together!

Refer to articles and books

  • Everest Architecture Course (highly recommended)
  • Analyze the internal operation mechanism of vue.js
  • Vue. Js
  • Vue 2.0 learning notes: Vue render function
  • Top tier Internet enterprise front-end JavaScript interview revealed
  • Some understanding of Virtual-dom
  • In-depth analysis: How to implement a Virtual DOM algorithm