13
votes

I understand that React creates a virtual DOM and compares the difference and then just updated the actual element of the real DOM but how is that more efficient if I change it manually? Via getElementById or by using the jQuery function?

<!DOCTYPE html>
<html>
<body>

<form>
Select your favorite browser:
<select id="myList" onchange="myFunction()">
  <option></option>
  <option>Google Chrome</option>
  <option>Firefox</option>  
  <option>Internet Explorer</option>
  <option>Safari</option>
  <option>Opera</option>
</select>
<p>Your favorite browser is: <input type="text" id="demo" size="20"></p>
</form>

<script>
function myFunction() {
    var mylist = document.getElementById("myList");
    document.getElementById("demo").value = mylist.options[mylist.selectedIndex].text;
}
</script>

</body>
</html>
1
What does your code have to do with your question?Amadan

1 Answers

25
votes

Changing Virtual DOM should not be much different than changing the real DOM. The problem is in the aftermath: changes in real DOM trigger relayout and repaint, so the less we touch the real thing, the better.

One way to do template rendering is to render the template, then replace the whole container element with newly rendered template. This needs to recalculate everything that just appeared within the container, and everything affected by it. Basically, if the browser was your kitchen and your template container a fridge (and your image of the fridge as it would be in five minutes, your virtual DOM), and you bought a lemon, typical template render would throw out your fridge, imagine what the fridge with a lemon would look like, buy all the ingredients you had before and also a lemon, then fill the new fridge.

The thing that React and other similar frameworks do that speeds this up is the diff process, that finds the minimal set of changes to get the real DOM to reflect the virtual DOM, which can drastically reduce the number of recalculations the browser will need to do in order to paint it. In the previous analogy, you imagine what your fridge would be like after you bought a lemon (fridge with no lemon vs fridge with a lemon), figure out the minimal change (add the lemon) and perform it.

It so happens that throwing out a fridge every time you change anything in it is kind of expensive.

Note that Virtual DOM is not quicker than simply fetching one element via getElementById and changing it. The comparison is between two ways of dealing with changes in complex subtrees, not single elements.