innerHTML vs removeChild vs jquery.empty

JavaScript performance comparison

Revision 120 of this test case created by Eamon Nerbonne

Info

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 code

<div id="box" style="display:none;"></div>
<script src="//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>
<script>
Benchmark.prototype.setup = function() {
    reset(true);
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

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

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment