2

I want to test the performance of some code snippets in JS using:

function perf() {
  var start = new Date()
  // the snippet codes
  var end = new Date()
  return end - start
}

then i wrote some sample code:

HTML:

<section>
    <button>insert list item</button>
    <ul></ul>
</section>

JS:

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)

The console output was: t1: 199 ms t2: 7332 ms

It looks like t2 is the performance i want, but wrap them with a deferred timer is weird, what is right way to do this? And why is t1 so fast?

1

Use Chrome's Timeline tool to measure performance.

  • Make a Timeline recording to analyze every event that occurred after a page load or a user interaction.

  • View FPS, CPU, and network requests in the Overview pane.

  • Click on an event within the Flame Chart to view details about it.

  • Zoom in on a section of a recording to make analysis easier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.