innerHTML vs remove lastChild with var

JavaScript performance comparison

Revision 306 of this test case created by

Preparation code

<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>
      
<script>
Benchmark.prototype.setup = function() {
  reset(true);

};
</script>

Preparation code output

<div id="box" style="display:none;"></div> <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>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
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
var i;
while (i=box.firstChild) {
        i.remove();
}
reset();
pending…
remove firstChild with null check
while (box.firstChild !== null) {
	box.removeChild(box.firstChild);
}
reset();
pending…
remove lastChild with var
var i;
while (i = box.lastChild) {
    i.remove();
}
reset();
pending…
textContent
box.textContent = '';
reset();
pending…
empty fragment
box.appendChild(fragment.cloneNode());
reset();
pending…
forEach
slice.call(box.childNodes).forEach(function(node) {
    box.removeChild(node);
});
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.

0 Comments