what is the difference between gift and virtual gift?

10

I saw a framework that worked with virtual dom and for that fact it became faster than the others. (framework: facebook reactjs)

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

Example in pure js

    
asked by anonymous 07.12.2014 / 17:08

3 answers

12

Difference between DOM and Virtual DOM

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

Virtual DOM is a framework for DOM manipulation.

How Virtual DOM works

Virtual DOM offers three features:

  • A representation of the real DOM in the JavaScript language. The actual DOM is then generated from this representation.
  • Computing the differences between the actual DOM and its representation.
  • Patch application to update the actual DOM according to the new state of its representation.

So, using Virtual DOM you:

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

Why Virtual DOM is faster

It is not necessarily faster. It may be faster if your code to check and manipulate the DOM is not as efficient as the code itself.

What is the advantage and disadvantage in each

Since DOM and Virtual DOM are two distinct things, there is no way to compare them.

What can be compared is the Virtual DOM with another mechanism to manipulate the DOM (pure JavaScript , JQuery or other frameworks such as BackboneJS and AngularJS ).

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

Going further in the list of advantages and disadvantages seems to me to come to the opinion, and I can not even say because I've never used Virtual DOM.

Example of using Virtual DOM

Retrieved from the 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 the Virtual DOM repository in GitHub .

  

Manually manipulating the DOM is a mess and keeping track of the status   the DOM is difficult. One solution to this problem is to write   your code as if you were re-creating the entire DOM every time you   the state changed. Of course, if you did in fact recreate the entire DOM   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 DOM. So instead of updating the DOM   when the state of your application changes, you simply create a   virtual tree (or "VTRee"), which looks like the state you   want for the DOM. Virtual-DOM will then figure out how to make the DOM   to be equal to this virtual tree (with the same state of it) of way   efficient, without re-creating all DOM nodes.

     

Virtual-DOM allows you to update the view whenever the state changes   through VTRee's complete recreation of the view and through the efficient   updating the DOM so that it looks exactly like you   described. This results in maintaining manual manipulation of the DOM and also   state tracking out of your code, promoting a logic of   clean and easy-to-maintain renederation for Web applications.

Other sources:

10.12.2014 / 14:05
2

Virtual Dom code:

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;

Gift Code:

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

The site has a test case.

    
10.12.2014 / 11:18
1

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

And then we have a smaller, unlinked DOM object, so we can modify it and use it much more quickly, with no need to get the DOM again, only on a few small occasions, but out of shape very fast .

So you can understand that Virtual DOM is faster, after all what would be better, manipulate a unlinked small object or manipulate an object inside the DOM which is a huge tree of objects? / p>

The advantage of it is this performance that is achieved by these facts, Your downside would not be as complete as the DOM, but I believe this would not be a problem , since there is a lot in the DOM so that you can use it completely.

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

There are some frameworks and some libs that are currently using virtual-dom, among them I mention some:

Libs

  • React
  • Virtual-DOM
  • Frameworks

  • Elm
  • Mercury
  • Mithril
  • Om
  • Ractive
  • Tagtree
  • WebSharper.UI.Next
  • Examples:

  • Why React is Awesome
  • React + D3
  • D3 in a virtual room + domino.js
  • AngularJS + React
  • Pedestal + Om
  • React + bacon.js
  • Reference:

    What is a virtual dom?

        
    09.12.2014 / 17:59