appendChild vs. DocumentFragment vs. innerHTML (v29)

Revision 29 of this benchmark created by utyf on


Description

Comparing 3 different ways to dynamically insert new elements into the DOM tree.

Preparation HTML

<div id="test1"></div>
<script>
window.content = {
    // a simple string to be attached via innerHTML
    string: '<div>Testing innerHtml and DOM-based methods on <strong>massive</strong> add.</div>',

    // a node to be attached using DOM methods
    dom: (function () {
        var node, strong;
        node = document.createElement('div');
        node.appendChild(document.createTextNode('Testing innerHtml and DOM-based methods on '));
        strong = document.createElement('strong');
        strong.appendChild(document.createTextNode('massive'));
        node.appendChild(strong);
        node.appendChild(document.createTextNode(' add.'));
        return node;
    })()
};
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
innerHTML
var div1 = document.getElementById("test1"),
    content = window.content,
    html = [];

for (var i = 0; i < 1000; i++) {
    html.push(content.string);
}

div1.innerHTML = html.join('');
div1.innerHTML = '';
ready
DocumentFragment
var div1 = document.getElementById("test1"),
    content = window.content,
    frag = document.createDocumentFragment();

for (var i = 0; i < 1000; i++) {
    frag.appendChild(content.dom.cloneNode(true));
}

div1.appendChild(frag);
div1.innerHTML = '';
ready

Revisions

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