DOM Tree creation

Benchmark created by Lance on


Description

Test to see if complex tree is faster with innerHTML or native DOM, once factoring in string concat etc.

Preparation HTML

<div id="myTest"></div>

Setup

var structure = {
        attributes: {
        class: 'outerClass',
        ID: 'outerID'
        },
        text: 'hello1',
        children: [
        {
            attributes: {
                class: 'innerClass',
                ID: 'innerID1'
            },
            text: 'hello2',
        }, {
            attributes: {
                class: 'innerClass',
                ID: 'innerID2'
            },
            text: 'hello3',
        }
        ]
    };
    
    
    function buildInnerHTML(structure) {    
        var aLines = [];
        function createHTMLArray(node) {
        aLines.push('<div ');   
        for (var attribute in node.attributes) {
            aLines.push(attribute);     
            aLines.push('="');  
            aLines.push(node.attributes[attribute]);    
            aLines.push('" ');          
        }
        aLines.push('">');
        if (node.text) {
            aLines.push(node.text + ' innerHTML');
        }
        if (node.children) {
            for (var c = 0, cl = node.children.length; c < cl; c++) {
                createHTMLArray(node.children[c]);
            }
        }
        aLines.push('</div>');
        }
        createHTMLArray(structure);
        return aLines.join('');
    }
    
    function buildDomTree(structure) {
        var domTree = document.createElement('div');
        if (structure.text)     domTree.appendChild(document.createTextNode(structure.text + ' Native'));
        for (var attribute in structure.attributes) {
        domTree.setAttribute(attribute, structure.attributes[attribute]);
        }
        if (structure.children) {
        for (var c = 0, cl = structure.children.length; c < cl; c++) {
            domTree.appendChild(buildDomTree(structure.children[c]));
        }
        }
        return domTree;
    }

Teardown


    document.getElementById('myTest').innerHTML = '';
  

Test runner

Ready to run.

Testing in
TestOps/sec
innerHTML
document.getElementById('myTest').innerHTML = buildInnerHTML(structure);
ready
Native
document.getElementById('myTest').appendChild(buildDomTree(structure));
ready

Revisions

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