One, foreword

Now web front-end development, for the use of MVVM framework, that is handy, with the fly. An XXX-CLI tool can initialize a set of templates, fill in the business code, and package deployment. But knowing how to use it is one aspect. Do you think deeply about the technical breakthrough point at the core of these frameworks? What problems have been solved? As active learners, we need to take a little time to do a little research. Today, we’ll take a brief look at the virtual DOM to demystify it.

Let’s start with a classic interview question:

“Why do we need the virtual DOM? .

A common response to this question is: “DOM manipulation is slow, JS is fast, and direct manipulation of DOM can result in frequent backflow and redraw, which is not a problem with JS. So the virtual DOM is faster than the native DOM.”

But is this really the case?

What is the virtual DOM? What.

Virtual DOM (Virtual DOM) is essentially a mapping cache between JS and DOM, which is represented as a JS object that can describe the DOM structure and its attribute information. It is stored mainly in memory. Mainly speaking:

  • 1. The virtual DOM is a JS object
  • 2. Virtual DOM can describe real DOM (there is a correspondence)
  • 3. It is stored in the MEMORY

Using react as an example, let’s see what the virtual DOM looks like:

Why is there a virtual DOM? According to.

First, let’s take a look at how we used to manipulate dom in ancient times (maybe seven or eight years ago).

1. Nothing, native JS

How do we find elements in native JS

According to the name of the class / / query elements, returns an array of satisfy the query conditions of the document. The getElementsByClassName () / / according to the tag name query elements, Returns an array of satisfy the query conditions of the document. The getElementsByTagName () / / according to the tag name query element, return a result satisfy the query conditions document. The getElementById ()...Copy the code

How do we dynamically modify the DOM

var displayName = 'hello,admin';
document.getElementById('#id').innerHtml = '<div>' + displayName+'</div>';

window.document.body.append('<div>hahahha</div>');

Copy the code

Do you think it’s efficient to manipulate the DOM this way?

2. Jquery era

JQuery encapsulates THE DOM API in a relatively simple and elegant form while simultaneously eliminating cross-browser compatibility and providing a series of capabilities such as chained API calls and plug-in extensions to further free up productivity. The end result is the much-loved “write less, do more”.

JQuery makes DOM manipulation simple, fast, and always stable in form and availability. Although it seems not perfect now, but in those days to be able to unify all corners of the country, really in the liberation of productivity, improve efficiency has a great role in promoting.

$('#id').show();
$('.className').hide().html('xxxxx');
Copy the code
Template engines

Let’s take the Handlebars template as an example

<! -- Include Handlebars from a CDN --> <script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.js"></script> <script> // compile the template var template = Handlebars.compile("Handlebars <b>{{doesWhat}}</b>"); // execute the compiled template and print the output to the console console.log(template({ doesWhat: "rocks!" })); </script>Copy the code
{
  people: [
    "Yehuda Katz",
    "Alan Johnson",
    "Charles Jolley",
  ],
}
Copy the code
 <ul class="people_list">
  {{#each people}}
    <li>{{this}}</li>
  {{/each}}
</ul>
Copy the code

With template engine, to operate JS, the efficiency is quite high, cool crooked ah. Every time the data changes, we don’t have to worry about where the data changed, and we don’t have to manually modify the DOM point-to-point. Just focus on the data and the data changes themselves, and the DOM level change template engine will do that for us.

There are many similar template engines, and we can compare their performance:

The template engine is like a “sweeper robot” that just needs to take orders to do a good job! Unfortunately, the template engine was created to separate the user interface from the business data, but the actual application scenario is basically limited to achieving efficient string concatenation, so you can’t expect it to do anything too complicated. Especially unacceptable is its performance: it is not “smart” enough to update the DOM by deregistration of the entire DOM, and there is no update buffer. In the case of frequent DOM operations, the template engine may directly cause the page to freeze.

That said, we want to manipulate the DOM efficiently and quickly, while still maintaining good performance. You modify the local DOM and replace the local. Not the whole thing. But if you’re always working with the real DOM, and you’re always logging out of the DOM as a whole and then re-rendering the whole dom as a whole, then performance is compromised. —- React team thought about it, we can operate fake DOM?

So the virtual DOM was born naturally.

How does the virtual DOM work? How.

To illustrate, borrow a picture of The Great God:

From this figure, we can conclude:

Data + template => virtual DOM

The template here is not necessarily a JS template engine like Handlebars. In React, this template exists in a JSX situation. JSX is a syntactic extension of Javascript. You can interpret react as using javascript syntax sugar that is similar to the template experience.

This is an extra buffer compared to the traditional way of modifying the DOM. When DOM operations (rendering updates) are frequent, it will first compare the two virtual DOM trees, locate the specific parts that need to be updated, and generate a “patch set”. Finally, only the “patch” is put on the part of the real DOM that needs to be updated, achieving accurate “differential update”.

Note that vue supports the virtual DOM as well, using react as an example. The virtual DOM, in other words, is framework-independent. React is the virtual DOM. To learn react, you need to understand the virtual DOM.

Throughout the evolution of DOM manipulation, the main contradiction was not performance, but the development experience/development efficiency (how well the developer wrote it). The virtual DOM is nothing more than a high-order product created by front-end developers in pursuit of better r&d experience and efficiency.

The Virtual DOM doesn’t necessarily lead to better performance, and React has never officially advertised the virtual DOM as a performance selling point. The advantage of the virtual DOM is that it can provide a more streamlined and efficient mode of development (i.e., functional UI programming) while still maintaining decent performance.

Four, performance analysis and comparison

  • The process of dynamically generating HTML strings is essentially the concatenation of strings, and the performance consumption is limited. However, the virtual DOM construction and diff process logic are relatively complex, which inevitably involves time-consuming operations such as recursion and traversal. So in terms of JS behavior, template rendering wins.

  • Both the template and the virtual DOM are DOM-specific actions in the final DOM update phase, and they are comparable, so we can still happily compare them: template rendering is a full update, while the virtual DOM is a differential update.

In general, updates are more efficient than full updates, but you need to consider a situation where the content of the data changes so much (or the whole thing changes) that the differential update computes very close (or exactly the same) to the full update. Then the virtual DOM has no performance advantage in the DOM update phase.

In this case, the DOM update effort is basically the same, while the virtual DOM is accompanied by more expensive JS calculations. One of the things that can happen is that template rendering and the virtual DOM are very much the same in terms of overall performance: If the DOM updates calculated by the two are exactly the same, the virtual DOM is likely to lose to template rendering. But if the two are even slightly apart in the amount of final DOM manipulation, the virtual DOM will have the edge over template rendering. Because the disadvantage of virtual DOM mainly lies in the time consuming of JS computation, and the energy consumption of DOM operation and JS calculation are not of the same magnitude at all, the performance consumption of a very small amount of DOM operation is enough to support a large number of JS computation.

In real development, the more common scenario is that I only modify a small amount of data each time I setState, such as a few properties in an object, or a few elements in an array. In such a scenario, the DOM manipulation gap between template rendering and the virtual DOM is completely opened, and the virtual DOM will have an absolute advantage in performance.

At the same time, let’s consider the situation where three states can be changed in a short period of time and react can add the virtual DOM buffer to the batch update task. Instead of constantly updating immediately every time is dom.

The meaning of virtual DOM

Back to the original question: Why do we need the virtual DOM?

Throughout the evolution of DOM manipulation, the main contradiction was not about performance, but about how well the developer wrote it, and about the development experience/development efficiency. The virtual DOM is nothing more than a high-order product created by front-end developers in pursuit of better r&d experience and efficiency. The Virtual DOM doesn’t necessarily lead to better performance, and React has never officially advertised the virtual DOM as a performance selling point. The advantage of the virtual DOM is that it can provide a more streamlined and efficient mode of development (i.e., functional UI programming) while still maintaining decent performance.

The virtual DOM solves two key problems.

  • 1. Research and development experience/research and development efficiency: This point has been repeatedly emphasized before, behind every innovation of DOM operation mode, is the front-end’s further pursuit of efficiency and experience. The emergence of virtual DOM provides a highly available vehicle for the idea of data-driven view, enabling front-end development to achieve efficient declarative programming based on functional UI programming.

  • 2. Cross-platform issues: The virtual DOM is a layer of abstraction over real rendered content. Without this layer of abstraction, the view layer is tightly coupled to the rendering platform, and you may have to write two or more completely different sets of code on the Web and Native side to describe the same view content. But now there is a layer of descriptive virtual DOM in the middle, which describes things that can be real DOM, iOS interface, Android interface, small programs…… The same set of virtual DOM can be connected with the rendering logic of different platforms, so as to achieve “once coding, multi-terminal operation”.

At the end of the day, solving cross-platform problems is also about improving r&d efficiency.