innerHTML vs removeChild

JavaScript performance comparison

Revision 178 of this test case created

Info

what method for empty a element is faster ?

Preparation code

<div id="container"></div>
<style type="text/css">
    #box, #box * {
        font-size: 0;
    }
    #box * {
        display: inline-block;
        width: 1px;
        height: 1px;
        padding: 0;
        margin: 0;
        background-color: blue;
    }
</style>
<script>
Benchmark.prototype.setup = function() {
    var box = document.createElement('div');
    box.id = 'box';
    document.getElementById('container').appendChild(box);
    var CHILDREN = 10000;
    function refill() {
        for (var i = box.childNodes.length; i < CHILDREN; i++)
        box.appendChild(document.createElement('div'));
    }
   
};

Benchmark.prototype.teardown = function() {
    document.getElementById('container').removeChild(box);
};
</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
remove first child
refill();
while (box.firstChild)
  box.removeChild(box.firstChild);
pending…
remove last child
refill();
while (box.lastChild)
  box.removeChild(box.lastChild);
pending…
innerHTML
refill();
box.innerHTML = '';
pending…
textContent
refill();
box.textContent = '';
pending…
hasChildNodes
refill();
while (box.hasChildNodes())
  box.removeChild(box.firstChild);
pending…
check first child
refill();
var firstChild;
while ((firstChild = box.firstChild) !== null)
  box.removeChild(firstChild);
pending…
remove by reference foreach
refill();
Array.prototype.slice.call(box.childNodes, 0).forEach(function (node) {
    box.removeChild(node);
});
pending…
remove by reference loop
refill();
var rubbish = box.childNodes;
for (var i = rubbish.length - 1; i >= 0; i--)
    box.removeChild(rubbish[i]);
rubbish = undefined;
pending…
shallow clone
refill();
var box2 = box.cloneNode(false);
box.parentNode.replaceChild(box2, box);
box = box2;
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