A simple understanding of virtual dom

Virtual dom

Frequent and complex dom operations are usually the origin of front-end performance bottlenecks, Vue provides a solution for virtual dom

The core idea of ​​the virtual DOM is: to provide a convenient tool for the complex DOM structure of the document, to minimize the DOM operation. This sentence may be too abstract, but it basically summarizes the design ideas of virtual DOM

(1) Provide a convenient tool to ensure the development efficiency
(2) Minimize the DOM operation and ensure the execution efficiency

That is to say, the framework / tools of virtual dom do this:

  1. According to the virtual dom tree, it is initially rendered into a real dom
  2. When the data changes, or when the page needs to be re-rendered, a new complete virtual dom will be regenerated
  3. Compare the new virtual dom with the old virtual dom (using the diff algorithm). After getting the place that needs to be updated, update the content

In this way, it can greatly reduce the operation of the real dom and improve performance

Insert picture description here

example:


<body>

    
    <div id="content">
        <p>{{ 1+1}}</p>
        <ul class="list-group">
            
        </ul>
    </div>

    <div id="myp">1</div>
    <script src="./base/vue.js"></script>

    <script>

         //执行10000次代码  0.3ms
        let myp = document.getElementById("myp")
        let num = 1
        console.time("temp")
        for(var i=0;i<10000;i++){
            num++
        }
        myp.innerHTML = num
        console.timeEnd("temp")
        

        
        //执行10000次代码  35ms
        console.time("temp")
        for(var i=0;i<10000;i++){
            let num = myp.innerHTML*1
            myp.innerHTML = ++num
        }
        console.timeEnd("temp")


    </script>

</body>

Effect: After
Insert picture description here
running, you will find that the first algorithm takes more than a hundred times faster than the second algorithm! ! Why is this? This is because the first algorithm operates on the virtual dom in memory ( virtual dom is actually a memory-type object (js memory object) which belongs to a layer of mapping of real dom of memory data) , and then performs operations in the virtual dom When rendering to the page, the second kind is to operate the real dom, so the performance consumed in the second is much more than the first, and naturally it is slower than the first.

Don't understand? Let's take another example

<body>
    
    <div id="content">
        <p>{{ 1+1}}</p>
        <ul class="list-group">
            
        </ul>
    </div>

    <div id="myp">1</div>
    <script src="./base/vue.js"></script>

    <script>

        //在vue内部的话,其实有虚拟dom
        var data = {
            arr:[]
        }

        //1.在渲染之前内存中会首先生成一颗虚拟dom树      
        var vDom = {
            tag:"div",
            attr:{
                id:"content"
            },
            children:[
                {tag:"p",content:2},
                {tag:"ul",attrs:{className:"list-group"}}
            ]
        }

        //2.将内存中的虚拟dom树初始化渲染成真实dom树
        //3.当我们修改data里面的数据的时候
        data.arr.push("<li>111111</li>")
        data.arr.push("<li>222222</li>")
        //4.将之前的虚拟dom树结合新的数据生成一颗新的虚拟dom树
        var newDom = {
            tag:"div",
            attr:{
                id:"content"
            },
            children:[
                {tag:"p",content:2},
                {tag:"ul",attrs:{className:"list-group"},children:[
                    {tag:"li",content:"11111"},
                    {tag:"li",content:"22222"}
                ]}
            ]
        }
        //5.将此次生成好的新的虚拟dom树与上一次的虚拟dom树结构进行对比,对比差异(diff算法)
        //6.将对比出来的差异的部分进行重新真实dom结构的渲染
        </script>
    </script>

What is virtual dom? Relationship with key value?
Virual DOM records a copy of a dom node with a JS object. When the dom changes, first use the
virtual dom to perform diff, calculate the minimum difference, and then modify the real dom.

  • When manipulating the DOM in the traditional way, the browser will execute the process from the beginning to the end of building the DOM tree, which is very inefficient. The virtual DOM is represented by javascript objects, and operating javascript is very simple and efficient. There is a layer of mapping between virtual DOM and real DOM. Many places that need to operate DOM will operate virtual DOM, and finally update DOM uniformly. So you can improve performance

Diff algorithm of virtual DOM

In the virtual DOM, when the state of the DOM changes, the virtual DOM will perform a Diff operation to update the DOM that only needs to be replaced, instead of redrawing all.
In the Diff algorithm, only the nodes of the two DOM trees before and after the comparison are flat, and no depth traversal is performed.

1. If the node type is changed, the old node is directly uninstalled and replaced with a new node. The old node including the following child nodes will be uninstalled. If the new node and the old node are only of different types, but all the child nodes below are the same This is also a place where efficiency is not high.
2. The node type does not change, the attribute or attribute value changes, the node will not be uninstalled, and the node update operation will be performed.
3. Change the text, directly modify the text content.
4. When moving, adding, or deleting child nodes:

If you want to insert node F in the middle, the simple and crude approach is: unload C, load F, unload D, load C, unload E, load D, load E. As shown below:

Insert picture description here

When writing code, if you do not define a key for the array or enumeration type, the above brute force algorithm will be used.
If you add a key to an element, Vue can directly find a specific location to operate according to the key, and the efficiency is relatively high. As shown below:

Insert picture description here

This seeks the principle that the same key value can be reused.

Providing the key in v-for can improve performance on the one hand and avoid errors on the one hand

Published 31 original articles · Liked4 · Visitors1003

Guess you like

Origin blog.csdn.net/qq_43942185/article/details/105060233