K
K
KirylLapouski2018-06-11 15:33:27
JavaScript
KirylLapouski, 2018-06-11 15:33:27

Why is inserting into a virtual dom faster than inserting into a regular one?

Is a single change in the virtual dom faster than the same change in the real one? Why?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-06-11
@KirylLapouski

You must understand that when a React component is rendered, the following things happen:
1. calculation of a new Virtual DOM node
2. adding elements to the real DOM based on the received Virtual DOM model,
when a React component is re-rendered, something like the following happens:
1. calculation of a new version of the node Virtual DOM
2. checking it with the old one
3. if necessary, changes are made to the real DOM
Therefore, your question is not posed correctly. If you change the Virtual DOM without changing the regular DOM afterwards, you won't see any changes on the Web page. Since it's just an object in your application's memory:

{
  type: 'ul', props: { 'class': 'list' }, children: [
    { type: 'li', props: {}, children: ['item 1'] },
    { type: 'li', props: {}, children: ['item 2'] }
  ]
}

React itself changes the DOM more slowly than if you were to change it directly. Since, in addition to the DOM change itself, it is necessary to calculate the new version of the Virtual DOM, compare it with the old one, and only then make changes. You can read about it in the articles below.
Related articles:
Why Virtual DOM is slower
Benchmark
How Virtual DOM works
How to write your own virtual DOM

S
Stalker_RED, 2018-06-11
@Stalker_RED

Because when inserted into a regular one, reflow and / or repaint occurs .
Some parts of the page are redrawn, and this is the load and time.
For the same reason, when inserting into a regular DOM, it is more profitable to collect a large piece and insert it in one step, instead of inserting multiple small elements.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question