Understand how inefficient for browsers to create DOM node - kdaisho/Blog GitHub Wiki

The DOM tree makes it easy for us to create, update, and delete nodes, however, the direct manipulation of that tree tends to be really slow when we have a large number of nodes.

Let’s write some code to find out how long it takes to update a DOM node compared to a simple string.

Paste the code below into a browser console window.

// ========= Updating String =========

let someString = "some string"

function updateString() {
  for (let i = 0; i <= 10000; i++) {
    someString = "update string"
  }
}

const t1 = performance.now()
updateString()
const t2 = performance.now()

console.log("It took " + (t2 - t1) + " milliseconds to update string");


// ========= Updating DOM =========

const newDiv = document.createElement("div")
const newText = document.createTextNode("some text")

newDiv.appendChild(newText)
document.body.appendChild(newDiv)

function updateDom() {
  for (let i = 0; i <= 10000; i++) {
    newDiv.innerHTML = "updated text"
  }
}

const t3 = performance.now()
updateDom()
const t4 = performance.now()

console.log("It took " + (t4 - t3) + " milliseconds to update a DOM");

The code above should print something like this.

It took 0.5 milliseconds to update the string
It took 66.69999998807907 milliseconds to update a DOM

Updating DOM takes 135 times longer than updating a string! This is why smart people have invented the virtual DOM.