What is the difference between DOM and virtual DOM?

Asked

Viewed 8,663 times

20

I saw a framework that worked with Virtual DOM and thus became faster than the others. (framework : facebook reactjs)

What is the advantage and disadvantage in each one? How to work with each one?

Example in pure js

3 answers

21

Difference between DOM and Virtual DOM

GIFT is the representation of the components on the page. You manipulate the DOM in order to manipulate these components (create, recreate, change their state).

Virtual DOM is a framework for DOM manipulation.

How the Virtual DOM works

Virtual DOM offers three features:

  • A representation of the real DOM in the Javascript language. The real DOM is then generated from this representation.
  • Computing the differences between the real DOM and its representation.
  • Application of patch to update the real DOM according to the new state of its representation.

In this way, using Virtual DOM you:

  • 1) Creates a DOM representation in the Virtual DOM language;
  • 2) Have the Virtual DOM generate the real DOM;
  • 3) When there is change in the model, instead of updating the real DOM you simply have the entire Virtual DOM representation regenerated by passing the new model state as parameter;
  • 4) Then you use the comparison mechanism to get the differences between the representation of the Virtual DOM and the real DOM;
  • 5) And uses the patch mechanism that will update the actual DOM as observed differences.

Why Virtual DOM is faster

It’s not necessarily faster. It can be faster if your code to verify and manipulate the DOM is not as efficient as its code.

What is the advantage and disadvantage in each one

As DOM and Virtual DOM are two different things, there is no way to compare them.

What can be compared is the Virtual DOM with another mechanism to manipulate the DOM (Javascript pure, Jquery or other frameworks such as Backbonejs and Angularjs).

In this case, on the advantage of the Virtual DOM, although the propaganda of the React Whether he is faster to use Virtual DOM, the propaganda of Virtual DOM itself says that its main advantage is the organization of the code, which makes it more significant, and the ability it offers you to focus on things other than the manipulation of the DOM. Of course he also states that he does all this in a very performative way.

To go beyond the list of advantages and disadvantages seems to enter the opinionated, and I can’t even opine because I’ve never used Virtual DOM.

Example of using Virtual DOM

Obtained from Virtual DOM repository on Github.

var h = require('virtual-dom/h');
var diff = require('virtual-dom/diff');
var patch = require('virtual-dom/patch');
var createElement = require('virtual-dom/create-element');

// 1: Cria a função que declara como o DOM deve ser
function render(count)  {
    return h('div', {
        style: {
            textAlign: 'center',
            verticalAlign: 'center',
            lineHeight: (100 + count) + 'px',
            border: '1px solid red',
            width: (100 + count) + 'px',
            height: (100 + count) + 'px'
        }
    }, [String(count)]);
}

// 2: Inicializa o documento
var count = 0;  // Precisamos de algum dado do aplicativo. Aqui nós apenas armazenamos um contador.

var tree = render(count);               // Nós precisamos de uma árvore inicial (representação do DOM)
var rootNode = createElement(tree);     // Cria um nó raiz DOM inicial a partir da representação...
document.body.appendChild(rootNode);    // ... e adiciona o nó raiz no documento

// 3: Dispara a lógica de atualização
setInterval(function () {
      // atualiza o dado do aplicativo  
      count++;
      // passando como parâmetro o dado atualizado, recria uma árvore completa para representar a view
      var newTree = render(count);
      // compara a representação recém criada com o DOM real e obtém as diferenças
      var patches = diff(tree, newTree);
      // aplica as diferenças no DOM real
      rootNode = patch(rootNode, patches);
      tree = newTree;
}, 1000);

Virtual DOM in the words of its creators:

Translated from Virtual DOM repository on Github.

Manual handling of DOM is a mess and keep track of the state previous DOM is difficult. A solution to this problem is to write your code as if you were recreating the entire DOM every time the state changed. Of course, if you actually recreate the entire GIFT once the application state changed, your application would be very slow and their input fields would lose focus.

Virtual-DOM is a collection of modules designed to provide a form declarative of representing the GIFT. So instead of updating the GIFT when the state of your application changes, you simply create a virtual tree (or "Vtree"), which looks like the state you wishes for the DOM. Virtual-DOM will then discover how to make the DOM be the same as this virtual tree (with the same state as it) so efficient, without recreating all nodes of the DOM.

Virtual-DOM allows you to update the view whenever the status changes through the complete recreation of Vtree’s view and through the efficient DOM update so it looks exactly like you described. This results in maintaining manual manipulation of the DOM and also state tracking outside of your code, promoting a logic of Clean and easy-to-maintain renederization for web applications.

Other sources:

  • In fact, the GIFT is not quite this. The GIFT is a model of the document, that is, as each element is arranged in its document, it is not a mechanism. And the virtual gift is not really a framework to manipulate the gift because in fact he does not manipulate the GIFT, he uses the GIFT as a basis to create his own GIFT, more reduced specified and organized, this at the time of its loading, because with a running application, when making changes, he does not access the GIFT, and yes your own Virtual DOM that was created.

  • and on: "patch application to update real DOM", This would cause Virtual DOM to lose its great advantage that would be not having to access the real DOM with each change, so it is fast. And of course it depends on your code but the slower it could get would equal the speed of the actual DOM.

  • @Pauloroberto DOM is a mechanism to manipulate the components the moment you manipulate the DOM in order to manipulate the components themselves. If it is not a "mechanism", it is a "middle" or suddenly another more appropriate word (feel free to edit). The rest of the answer I think leaves no doubt as to what it is. As to its other statements, they are all incorrect. There is no point in manipulating the Virtual DOM if it does not cause a result in the DOM itself. Read the documentation that Linkei.

  • @Pauloroberto I translated in my reply the linked page. Note how your vision is mistaken or at least incomplete. The whole purpose of Virtual DOM is precisely to manipulate the DOM. Nor would it make sense not to manipulate the DOM. If the DOM is not manipulated, as will be reproduced on the page the change of state of the application?

2

Virtual DOM, is nothing more than a Mini DOM, which is a small part of the GIFT, which would be the recreation of the DOM objects used containing only the necessary content, and leaving aside all the parts of the DOM that will not be used.

And then we have a smaller and detached object of the GIFT, so we can modify it and use it much more quickly, without any need to access the GIFT again, just on a few small occasions, but very quickly.

So you can understand that Virtual DOM is faster, after all what would be better, to manipulate a small detached object or manipulate an object within the DOM that is an immense tree of objects?

His advantage is this performance that is obtained through these facts, your disadvantage would be not as complete as the DOM, but I believe that this would not be a problem, because there is a lot in the DOM for you to be able to use it completely.

But not only that, Virtual DOM also becomes easier to maintain, because it’s more compact and less complex.

There are some frameworks and some libs that are currently using the virtual-gift, among them I quote some:

Libs

  1. React
  2. Virtual-DOM

Frameworks

  1. Elm
  2. Mercury
  3. Mithril
  4. Om
  5. Ractive
  6. Tagtree
  7. Websharper.UI.Next

Examples:

  1. Why React is Awesome
  2. React + D3
  3. D3 in a virtual room + domino.js
  4. Angularjs + React
  5. Pedestal + Om
  6. React + bacon.js

Reference:

What is a virtual dom?

2

Code in Virtual Dom:

var tree = virtualH('footer', {
    id: 'footer',
    className: 'footer'
}, [
    virtualH('span', {
        id: 'todo-count',
        className: 'todo-count'
    }, [
        virtualH('strong', String(todosLeft)),
        todosLeft === 1 ? ' item' : ' items',
        ' left'
    ]),
    virtualH('ul', {
        id: 'filters',
        className: 'filters'
    }, [
        virtualLink('#/', 'All', route === 'all'),
        virtualLink('#/active', 'Active', route === 'active'),
        virtualLink('#/completed', 'Completed', route === 'completed')
    ]),
    virtualH('button', {
        id: 'clear-completed',
        className: 'clear-completed',
        hidden: todosCompleted === 0
    }, 'Clear completed (' + String(todosCompleted) + ')')
]);
return tree;

Code in Dom:

var tree = domH('footer', {
    id: 'footer',
    className: 'footer'
}, [
    domH('span', {
        id: 'todo-count',
        className: 'todo-count'
    }, [
        domH('strong', String(todosLeft)),
        todosLeft === 1 ? ' item' : ' items',
        ' left'
    ]),
    domH('ul', {
        id: 'filters',
        className: 'filters'
    }, [
        domLink('#/', 'All', route === 'all'),
        domLink('#/active', 'Active', route === 'active'),
        domLink('#/completed', 'Completed', route === 'completed')
    ]),
    domH('button', {
        id: 'clear-completed',
        className: 'clear-completed',
        hidden: todosCompleted === 0
    }, 'Clear completed (' + String(todosCompleted) + ')')
]);
return tree;

Source: JSPERF

On the site there is a test case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.