Not All Loops Are Equal

Benchmark created on


Description

Testing the performance of all the different ways we can loop through an iterable collection of DOM Nodes.

Setup

let ul = document.createElement("ul");
for (let i = 0x400; i--; ul.appendChild(document.createElement("li")).textContent = i);

Teardown

ul.remove();
delete ul;

Test runner

Ready to run.

Testing in
TestOps/sec
Array.forEach
ul.querySelectorAll("li").forEach((li) => {
  li.classList.add("test");
  li.style.color = "red"; 
  li.textContent = "test";
});
ready
For..of
for (let li of ul.children) {
  li.classList.add("test");
  li.style.color = "red";
  li.textContent = "test";
}
ready
"Old School" for(index)
for (let i = 0, iLen = ul.children.length; i < iLen; i++) {
  ul.children[i].classList.add("test");
  ul.children[i].style.color = "red";
  ul.children[i].textContent = "test";
}
ready
"Old School" for(index) with single [index]
for (let i = 0, iLen = ul.children.length; i < iLen; i++) {
  let li = ul.children[i];
  li.classList.add("test");
  li.style.color = "red";
  li.textContent = "test";
}
ready
For on assignment

for (let i = 0, li; li = ul.children[i]; i++) {
  li.classList.add("test");
  li.style.color = "red";
  li.textContent = "test";
}
ready
While assignment
{
  let i = 0, li;
  while (li = ul.children[i++]) {
    li.classList.add("test");
    li.style.color = "red";
    li.textContent = "test";
  }
}
ready
if/do/while DOM walk
{
  let li = ul.firstElementChild;
  if (li) do {
    li.classList.add("test");
    li.style.color = "red";
    li.textContent = "test";
  } while (li = li.nextElementSibling);
}
ready
for DOM walk
for (let li = ul.firstElementChild; li; li = li.nextElementSibling) {
  li.classList.add("test");
  li.style.color = "red";
  li.textContent = "test";
}
ready

Revisions

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