test html element count calc

Benchmark created on


Preparation HTML

<div id="root"></div>

<script>
  const root = document.getElementById('root')

  const elementTypes = ['div', 'span', 'h3', 'h4', 'h5']

  function createNestedElements(parent, depth, maxDepth) {
    if (depth > maxDepth) return

    const elementType =
      elementTypes[Math.floor(Math.random() * elementTypes.length)]
    const element = document.createElement(elementType)

    element.textContent = `Element at depth ${depth}`

    parent.appendChild(element)

    createNestedElements(element, depth + 1, maxDepth)
  }

  for (let i = 0; i < 1000; i++) {
    createNestedElements(root, 1, 100)
  }

  function testQuerySelectorAll() {
    const elements = root.querySelectorAll('*')
    return elements.length
  }

  function testGetElementsByTagName() {
    const elements = root.getElementsByTagName('*')
    return elements.length
  }

  function testCustomTraverseRecursively() {
    let count = 0
    const traverse = node => {
      if (node.nodeType === Node.ELEMENT_NODE) {
        count++
      }
      if (node.firstChild) {
        traverse(node.firstChild)
      }
      if (node.nextSibling) {
        traverse(node.nextSibling)
      }
    }
    traverse(root)
    return count
  }

  function testCustomTraverseIteratively() {
    let count = 0
    const stack = [root]

    while (stack.length > 0) {
      const node = stack.pop()

      if (node.nodeType === Node.ELEMENT_NODE) {
        count++
      }

      if (node.firstChild) {
        stack.push(node.firstChild)
      }
      if (node.nextSibling) {
        stack.push(node.nextSibling)
      }
    }

    return count
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
test for querySelectorAll
for (let i = 0; i < 100; i++) {
  testQuerySelectorAll()
}
ready
test for getElementsByTagName
for (let i = 0; i < 100; i++) {
  testGetElementsByTagName()
}
ready
test for CustomTraverseRecursively
for (let i = 0; i < 100; i++) {
  testCustomTraverseRecursively()
}
ready
test for CustomTraverseIteratively
for (let i = 0; i < 100; i++) {
  testCustomTraverseIteratively()
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.