innerHTML vs remove lastChild with var (v309)

Revision 309 of this benchmark created by madreason on


Description

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

Updated 2013-12-13: make sure that there actually are elements to be deleted; jsperf setup does NOT run before each test, but before each test LOOP!!

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>
var fragment = document.createDocumentFragment();
for (var i=0;i<1000;i++){
    var c   = document.createElement('div');
    c.textContent = 'siodfj'+Date.now();
    fragment .appendChild(c);
}
function clearChildren(el) {
  var child;
  while(child=el.firstChild)
    el.removeChild(child);
}
var box = document.getElementById('box');
function reset(ignore) {
   if (!ignore && box.childNodes.length > 0) throw 'child nodes not cleared!';
   box.appendChild(fragment.cloneNode());
}
var slice = Array.prototype.slice;
</script>

Setup

reset(true);

Test runner

Ready to run.

Testing in
TestOps/sec
removeChild reversed
for (var nodes = box.childNodes, i = nodes.length - 1; i >= 0; i--) {
  box.removeChild(nodes[i]);
}
reset();
 
ready
innerHTML
box.innerHTML = '';
reset();
 
ready
jQuery empty
$(box).empty();
reset();
 
ready
remove firstChild
var child;
while (child = box.firstChild) {
        box.removeChild(box.firstChild);
}
reset();
 
ready
remove lastChild
var child;
while (child = box.lastChild) {
        box.removeChild(child);
}
reset();
 
ready
remove firstChild function
clearChildren(box);
reset();
 
ready
remove firstChild with var
var i;
while (i=box.firstChild) {
        i.remove();
}
reset();
 
ready
remove firstChild with null check
while (box.firstChild !== null) {
        box.removeChild(box.firstChild);
}
reset();
ready
remove lastChild with var
var i;
while (i = box.lastChild) {
    i.remove();
}
reset();
ready
textContent
box.textContent = '';
reset();
ready
empty fragment
box.appendChild(fragment.cloneNode());
reset();
ready
forEach
slice.call(box.childNodes).forEach(function(node) {
    box.removeChild(node);
});
reset();
ready
hasChildNodes
while (box.hasChildNodes()) {
        box.removeChild(box.lastChild);
}
reset();
ready

Revisions

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