removeChildren

JavaScript performance comparison

Revision 9 of this test case created

Info

From http://elv1s.ru/files/html+css/removeChildren.html

Test various ways of emptying an element of child nodes

Preparation code

<div id="container" style="display:none">
</div>
<script>
Benchmark.prototype.setup = function() {
    var container = document.getElementById('container'),
        proto = addelements(document.createDocumentFragment());
   
    function addelements(proto) {
      var i = 200,
          p, j, span;
      while (i--) {
        p = document.createElement('p');
        j = 5;
        while (j--) {
          span = document.createElement('span');
          span.appendChild(document.createTextNode(i * j + 'yada-yada'));
          p.appendChild(span);
        };
        proto.appendChild(p);
      };
      return proto;
    };
   
    function prepare() {
      container.appendChild(proto.cloneNode(false));
    };
};

Benchmark.prototype.teardown = function() {
    if (container.childNodes.length) {
        throw "Container was not emptied!";
    }
};
</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
innerHTML
prepare();

container.innerHTML = '';
pending…
textContent
prepare();

container.textContent = '';
pending…
remove firstChild with var
prepare();

var child;
while (child = container.firstChild) {
  container.removeChild(child);
}
pending…
remove lastChild with var
prepare();

var child;
while (child = container.lastChild) {
  container.removeChild(child);
}
pending…
remove firstChild direct
prepare();

while (container.firstChild) {
  container.removeChild(container.firstChild);
}
pending…
remove lastChild direct
prepare();

while (container.lastChild) {
  container.removeChild(container.lastChild);
}
pending…
remove by count lastChild
prepare();

var len = container.childNodes.length;
while (len--) {
  container.removeChild(container.lastChild);
}
pending…
remove by count firstChild
prepare();

var len = container.childNodes.length;
while (len--) {
  container.removeChild(container.firstChild);
}
pending…
remove hasChildNodes firstChild
prepare();

while (container.hasChildNodes()) {
  container.removeChild(container.firstChild);
}
pending…
remove hasChildNodes lastChild
prepare();

while (container.hasChildNodes()) {
  container.removeChild(container.lastChild);
}
pending…
forEach
prepare();

Array.prototype.forEach.call(container.childNodes, function(e) {
  this.removeChild(e);
}, container);
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