Different ways to rewrite a list (v2)

Revision 2 of this benchmark created by Tom Doan on


Description

Rewriting a list by traversing the DOM and using innerHTML / innerText / textContent, removing the entire list and using appendChild to reinsert it into the DOM, and by looping through a getElementsByTagName array.

Revision 2: Added childNodes method.

Preparation HTML

<ul id="test">
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>
 
<script>
  var oList = document.getElementById('test'),
      arr = ['c', 'b', 'a'];
  
  function li(node, text) {
   node.appendChild(document.createTextNode(text));
   return node;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
textContent
var oElm = oList.firstChild,
    i = 0;
while (oElm) {
 if (oElm.nodeType == 1) {
  oElm.textContent = arr[i++];
 }
 oElm = oElm.nextSibling;
}
ready
innerText
var oElm = oList.firstChild,
    i = 0;
while (oElm) {
 if (oElm.nodeType == 1) {
  oElm.innerText = arr[i++];
 }
 oElm = oElm.nextSibling;
}
ready
innerHTML
var oElm = oList.firstChild,
    i = 0;
while (oElm) {
 if (oElm.nodeType == 1) {
  oElm.innerHTML = arr[i++];
 }
 oElm = oElm.nextSibling;
}
ready
appendChild
while (oList.hasChildNodes()) {
 oList.removeChild(oList.firstChild);
}
var oFrag = document.createDocumentFragment();
for (var i = 0, imax = arr.length; i < imax; i++) {
 oFrag.appendChild(li(document.createElement('li'), arr[i]));
}
oList.appendChild(oFrag);
ready
getElementsByTagName
var aLi = oList.getElementsByTagName('LI');
for (var i = 0, imax = arr.length; i < imax; i++) {
 aLi[i].innerText = arr[i];
}
ready
childNodes
for (var i = 0, imax = oList.childNodes.length, j = 0; i < imax; i++) {
 if (oList.childNodes[i].nodeName == 'LI') {
  oList.childNodes[i].innerText = arr[j++];
 }
}
ready

Revisions

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

  • Revision 1: published by Tom Doan on
  • Revision 2: published by Tom Doan on
  • Revision 3: published by Marcus on