DEV Community

Cover image for Why VDOM vs. DOM comparison is biased and unfair
Jonatas de Moraes Junior
Jonatas de Moraes Junior

Posted on

Why VDOM vs. DOM comparison is biased and unfair

The most commonly used argument to justify the use of Virtual DOM is how fast it is compared to direct DOM manipulation.

Let's say you have to create a table with a hundred rows. If you create each element using vanilla javascript, it will be slower than creating them all in memory (vdom) and then dumping it to the real dom in a single iteration.

Well, obviously.

Making a change to the dom includes re-rendering of the page, it is much more computation than just changing values in-memory.

But you tell me: who on earth creates a hundred rows table by writing code for each element and then dumping element by element to the dom? Everybody knows this is not performant, and also this is just bad coding.

What you would want to do in order to develop a Single Page Application (SPA) is basically the same you would do while developing a server-side rendering application: you would want to use a template engine!

Template engines are pieces of software capable of processing a preset (template) against data in order to create dinamically generated content depending on the data. If you are creating a SPA (client-side rendering), this template processing has to happen in the client (browser), with data originating from a REST backend.

Let's take a look on how this would work while using Handlebars, a very popular template engine:

  1. At first, you will create your html template in its own *.hbs file;
  2. You will precompile the templates to javascript functions at build time;
  3. The functions will be executed against data in runtime (browser memory) and they will return a string;
  4. This string, which represents a portion of HTML, will be dumped to the dom in a single iteration.

This means you can put the hundred rows table in a template and, in the end, the template itself will have just a few rows and the data will define how big the table will be.

The same principle of the VDOM applies: change everything you need to change in-memory, and only dump these changes to the dom when you're finished, using as less dom manipulation as necessary.

Of course VDOM has other advantages like data-binding, but bragging about "blazing-fast speed" while making a biased comparison against bad code seems just wrong to me. We have to be critical and learn to understand when you apple is being compared to another apple or to an orange.

If you wish to learn more about Handlebars, in this other post I talk about properly precompiling Handlebars templates. Happy coding!

Top comments (0)