test html element count calc (v3)

Revision 3 of this 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 countElementsWithQuerySelectorAll() {
    const elements = root.querySelectorAll('*')
    return elements.length + 1
  }

  function countElementsWithTagNames() {
    const elements = root.getElementsByTagName('*')
    return elements.length + 1
  }

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

  function countElementsIteratively() {
    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 !== root && node.nextSibling) {
        stack.push(node.nextSibling)
      }
    }

    return count
  }

Test runner

Ready to run.

Testing in
TestOps/sec
countElementsWithQuerySelectorAll
countElementsWithQuerySelectorAll()
ready
countElementsWithTagNames
countElementsWithTagNames()
ready
countElementsRecursively
countElementsRecursively()
ready
countElementsIteratively
countElementsIteratively()
ready

Revisions

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