Different ways to rewrite a list (v3)

Revision 3 of this benchmark created by Marcus 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.

Revision 3: Added innerHTML on parent method, and some more complex html.

Preparation HTML

<style>
li { /*fixed size can improve performance*/
  width: 200px;
  height: 30px;
  overflow: hidden;
}
</style>

<ul id="test">
  <li my_id="a" title="a">a</li>
  <li my_id="b" title="b">b</li>
  <li my_id="c" title="c">c</li>
  <li my_id="d" title="d">d</li>
  <li my_id="e" title="e">e</li>
  <li my_id="f" title="f">f</li>
  <li my_id="g" title="g">g</li>
  <li my_id="h" title="h">h</li>
  <li my_id="i" title="i">i</li>
  <li my_id="j" title="j">j</li>
</ul>
 
<script>
  var oList = document.getElementById('test'),
      arr = ['j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'];
  
  function li(node, text) {
   node.appendChild(document.createTextNode(text));
   node.setAttribute('my_id', 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.setAttribute('my_id', arr[i]);
  i++;
 }
 oElm = oElm.nextSibling;
}
ready
innerText
var oElm = oList.firstChild,
    i = 0;
while (oElm) {
 if (oElm.nodeType == 1) {
  oElm.innerText = arr[i];
  oElm.setAttribute('my_id', arr[i]);
  i++;
 }
 oElm = oElm.nextSibling;
}
ready
innerHTML
var oElm = oList.firstChild,
    i = 0;
while (oElm) {
 if (oElm.nodeType == 1) {
  oElm.innerHTML = arr[i];
  oElm.setAttribute('my_id', arr[i]);
  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];
 aLi[i].setAttribute('my_id', 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];
  oList.setAttribute('my_id', arr[j++]);
 }
}
ready
innerHTML on parent
var newhtml = '';

for (var i = 0, imax = arr.length; i < imax; i++) {
 newhtml += '<li my_id="'+arr[i]+'" title="'+arr[i]+'">'+arr[i]+'</li>';
}

oList.innerHTML = newhtml;
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