innerHTML vs remove lastChild with var (v302)

Revision 302 of this benchmark created by Nicolas Normand 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());
}
</script>

Setup

reset(true);

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]);
}
reset();
 
ready
innerHTML
box.innerHTML = '';
reset();
 
ready
jQuery empty
$(box).empty();
reset();
 
ready
remove firstChild
while (box.firstChild) {
        box.removeChild(box.firstChild);
}
reset();
 
ready
remove lastChild
while (box.lastChild) {
        box.removeChild(box.lastChild);
}
reset();
 
ready
remove firstChild function
clearChildren(box);
reset();
 
ready
remove firstChild with var
while (i=box.firstChild) {
        box.removeChild(i);
}
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

Revisions

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