preface

After reading the first chapter, I asked myself two questions:

  • What is the programming paradigm? What does it have to do with Vuejs?
  • Why do you need the virtual DOM?

After reading the content, ask yourself questions in order to make yourself better thinking, because learning without thinking is simply a waste of time, but not very good harvest.

Programming paradigm

There are three programming paradigms:

  • Imperative programming
  • Declarative programming
  • Functional programming

But view-level frameworks such as vue.js typically use imperative and declarative paradigms, and a good framework is implemented on the basis of choosing the right paradigms, or even incorporating the benefits of both paradigms.

Imperative framework

Imperative frameworks are characterized by a focus on process, and jQuery, which was popular earlier, is a typical imperative framework.

Let’s illustrate what an imperative framework is by implementing a simple requirement.

Requirement Description:

  • Get the button element below
  • I’m going to set the text “show message”
  • Add the corresponding click event for it, click the button and pop up the corresponding prompt “Hello world”.
  <button id="btn"></button>
Copy the code

Implementation requirements:

  • nativeJavaScriptImplement version
    var btn = document.querySelector('#btn') // Get the corresponding element
    btn.innerText = 'show message' // Set the text content
    btn.addEventListenner('click'.() = > { // Bind the click event
        alert('hello world')})Copy the code
  • jQueryImplement version
    $('#btn') // Get the corresponding element
        .text('show message') // Set the text content
        .on('click'.() = > { // Bind the click event
          alert('hello world')})Copy the code

As you can see, the code implementation process and the requirement description can have a corresponding relationship, and in the code implementation is actually the “process of doing things”, that is, no matter what language you use to implement the function, can be implemented according to the specific description.

Declarative framework

A declarative framework is characterized by a focus on results, such as Vuejs.

Again, here is an example of implementing the above functional requirements in combination with Vuejs:

<button id="btn" @click="() => { alert('hello world') }">show message</button>
Copy the code

It can be seen that the code implementation process is not exactly the same as the requirement description, but this Vuejs code can achieve the required results.

In other words, Vuejs encapsulates the implementation, which means that the internal implementation must be imperative, but the exposure to the user is declarative.

Why does Vuejs choose declarative

Declarative code does not perform better than imperative code

As mentioned earlier, Vuejs is declarative externally, but its internal implementation is imperative, which ultimately reverts to imperative in nature, so declarative code really doesn’t perform better than imperative code in this sense.

For example, now we need to change the text content of the front button to “Hello vue3”

Imperative code

The changes take effect immediately by executing the following code:

btn.textContent = 'hello vue3' // Modify directly
Copy the code

Declarative code

/ / before update<button id="btn" @click="() => { alert('hello world') }">show message</button>/ / updated<button id="btn" @click="() => { alert('hello world') }">hello vue3</button>
Copy the code

For Vuejs, after executing the above code, it still needs to find the differences and update only the changes, but the final update is done with the following code:

btn.textContent = 'hello vue3' // Modify directly
Copy the code

Assuming that A is the performance cost of direct modification and B is the performance cost of finding the difference, then:

  • Update performance cost of imperative code = A
  • Update performance cost for declarative code = B + A

Even in the best-case scenario (where the performance cost of making a difference is 0, that is, B = 0), declarative code will have the same performance cost as imperative code, but not more than that.

Reasons for choosing declarative

Conclusion: Imperative code is a better choice for performance than declarative code.

So why did Vuejs choose a declarative design?

The reason is that declarative code is more maintainable:

  • In the development process of imperative code, users should pay attention to the whole process of achieving goals, including creation, update and deletion of DOM elements, which means that a large code volume requires more attention
  • Declarative code is much more intuitive and does not need to focus on the implementation, because the implementation is wrapped inside the framework, so the presentation of declarative code is what we want

There is a performance penalty when using declarative maintainability improvements, but the best result is to minimize the performance penalty while maintaining maintainability.

Why does Vuejs need a virtual DOM

why

As mentioned earlier, the performance cost of updating declarative code = the performance cost of finding the difference + the performance cost of directly modifying it, which means that as long as you minimize the performance cost of finding the difference, you can keep declarative code infinitely close to imperative code while maintaining maintainability.

Based on the previous theory, you can also conclude that the virtual DOM update technology is theoretically impossible to be any higher than the native JavaScript manipulation DOM. For the most part, it’s hard to write imperative code that is absolutely optimized, especially if the application is very large, and if you put a lot of effort into writing such code, the final input/output ratio is not very high.

Summary: The virtual DOM guarantees the use of declarative code while maintaining the performance of the application, or even optimizing the consumption of imperative code as much as possible.

How does the virtual DOM perform

The DOM performance is higher for the native JavaScript operations mentioned above, where the native JavaScript operations (createElement, etc.) do not include innerHTML because it is special.

Performance comparison of the virtual DOM and innerHTML

Requirement description: Generate the following real DOM structure:

<div>
 <span>hello world</span>
<div>
Copy the code

Implementation requirements:

The following are pseudo-code implementations

  • innerHTMLVersion implementation:
    const html = `
            
    hello world
    `
    document.body.innerHTML = html Copy the code
  • Virtual DOMVersion implementation:
    const app = {
        type:'div', 
        children:[
           {
             type: 'span'.children: 'hello world',}}]document.createElement(xxx)
    document.body.append(xxx)
    Copy the code

Create a stage

  • The performance of the innerHTML creation page = the amount of HTML string concatenation computation + the DOM computation of the innerHTML
  • Virtual DOM creation page performance = JavaScript object creation computation (virtual DOM) + real DOM creation computation

From the perspective of JavaScript level operations (HTML string concatenation and VNode object creation), the two are not that different, as they are BOTH JS operations and don’t involve the DOM.

From the DOM level (creating all the DOM elements), there’s not much difference, because all the DOM elements need to be created when the page is created.

Update the stage

  • The performance of the innerHTML creation page = the amount of HTML string concatenation computation + the DOM computation of the innerHTML
  • Virtual DOM creation page performance = creationnewJavaScript object count (virtual DOM) + Diff count + necessary DOM update count

At the JavaScript level (new HTML string concatenation, creation of a new virtual DOM object, and Diff comparison), the innerHTML takes the same amount of computation, but the virtual DOM adds an extra Diff computation.

The innerHTML creates a new HTML string, destroys all the old DOM elements, and then creates a new element entirely. The virtual DOM creates a new virtual DOM object, and Diff compares the old and new virtual DOM to find the changed element and update it.

Performance factors:

  • The virtual DOM is only concerned with data variation
  • The innerHTML is related to the size of the template

summary