DOM performance test

I'm having trouble testing the performance of some code that updates the DOM a lot.

To illustrate, I created a simple demo:

function insertListItem() {
  let ul = document.querySelector('ul')
  let start = new Date()
  
  // heavy dom operations
  for (let i = 0; i < N; i++) {
    let li = document.createElement('li')
    li.textContent = 'item' + i
    ul.appendChild(li)
  }
  
  // log the duration (deferred by 0ms timer)
  setTimeout(() => {
    let t2 = new Date() - start
    console.log(`t2: ${t2} ms`)
  }, 0)
 
  // log the duration instantly
  let t1 = new Date() - start
  console.log(`t1: ${t1} ms`)
}

let N = 100000
let btn = document.querySelector('button')
btn.addEventListener('click', insertListItem)
<section>
    <button>insert list item</button>
    <ul></ul>
</section>
Run code

Console output t1, t2a difference HUGE , which does not comply with my expectation, the code above, except the timer is synchronous. Due to the event loop, the timer callback will be placed in the callback / event queue and waiting for execution, this will undoubtedly lead to some delay between t1and t2, otherwise they should be approximately the same.

t1 , before the rendering task, t2 after the rendering task, . ? ?

+4

Source: https://habr.com/ru/post/1670810/


All Articles