innerHTML vs removeChild vs jquery.empty (v117)

Revision 117 of this benchmark created by Eamon Nerbonne on


Description

Which method to remove all content from an element is fastest?

Preparation HTML

<div id="box" style="display:none;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
function clearChildren(el) {
  var child;
  while(child=el.firstChild)
    el.removeChild(child);
}
</script>

Setup

var box = document.getElementById('box');
    for (var i=0;i<1000;i++){
        var c   = document.createElement('div');
        c.textContent = 'siodfj'+Date.now();
        box.appendChild(c);
    }

Teardown


    if (box.childNodes.length > 0) alert('child nodes not cleared!')
  

Test runner

Ready to run.

Testing in
TestOps/sec
removeChild reversed
for (var i = box.childNodes.length - 1; i >= 0; i--) {
  box.removeChild(box.childNodes[i]);
}
 
ready
innerHTML
box.innerHTML = '';
ready
jQuery empty
$(box).empty()
ready
remove firstChild
while (box.firstChild) {
        box.removeChild(box.firstChild);
}
ready
remove lastChild
while (box.lastChild) {
        box.removeChild(box.lastChild);
}
ready
remove firstChild function
clearChildren(box);
ready
remove firstChild with var
while (i=box.firstChild) {
        box.removeChild(i);
}
ready

Revisions

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