innerHTML or DOM

JavaScript performance comparison

Revision 18 of this test case created

Info

Most dynamic websites use innerHTML because they think it's faster. But is it? This compares hand-optimised DOM and innerHTML along with a sugared DOM and Handlebars templated version.

Handlebars, when compiled directly in the browser, cannot be run through a JIT optimization step, because it is constructed with the Function constructor (eval). Production environments are encouraged to use precompiled Handlebars templates.

Preparation code

<div id="targetEl" style="visibility: collapse"></div>
<script>
var HtmlFactory = (function () {
        "use strict";
        function unfoldArgumentInto(el, arr) {//can't check for window.Node: not available in IE8.
                var firstObj;
                var len;
                if (arr instanceof Array) {
                        len = arr.length;
                        if (len > 0)
                                firstObj = arr[0];
                        else
                                return el;
                } else {
                        firstObj = arr;
                        len = 1;
                }

                if (firstObj !== null && firstObj !== undefined) {
                        if (firstObj.nodeType)
                                el.appendChild(firstObj);
                        else if (firstObj instanceof Array)
                                unfoldArgumentInto(el, firstObj);
                        else
                                el.textContent = firstObj;
                }
                for (var i = 1; i < len; i++) {
                        var argVal = arr[i];
                        if (argVal !== null && argVal !== undefined) {
                                if (argVal.nodeType)
                                        el.appendChild(argVal);
                                else if (argVal instanceof Array)
                                        unfoldArgumentInto(el, argVal);
                                else  //assume it's text or convertable to text
                                        el.appendChild(document.createTextNode(argVal));
                        }
                }
                return el;
        };


        //Creates an element; returns a function for filling it.
        function forElem(elemName) {
                //Adds JS property/value pairs as attributes.  (onXXX properties that are functions are instead added as event handlers.)
                //returns a content-addition function
                function addAttrThenContent(attrContent) {
                        var el = document.createElement(elemName);
                        if (typeof attrContent === "object")
                                for (var prop in attrContent) {
                                        var propVal = attrContent[prop];
                                        if (propVal !== undefined) {
                                                if (typeof propVal === "function" && prop.substr(0, 2) === 'on') {
                                                        el.addEventListener(prop.substr(2), propVal, false);
                                                } else {
                                                        el.setAttribute(prop, propVal);
                                                }
                                        }
                                }

                        //Adds all arguments to the element's content.
                        return function (arr) {
                                return unfoldArgumentInto(el, arr);
                        };
                }

                function justAddContent(arr) { return unfoldArgumentInto(document.createElement(elemName), arr); };//addAttrThenContent();
                justAddContent.attrs = addAttrThenContent;
                return justAddContent;
        }

        var elNames = "a,abbr,address,article,aside,audio,b,blockquote,body,br,button,cite,code,del,details,dfn,div,em,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,img,input,ins,kbd,label,legend,li,link,mark,meta,meter,nav,noscript,ol,optgroup,option,p,pre,q,samp,script,section,select,small,source,span,strong,style,sub,summary,sup,table,tbody,td,textarea,tfoot,th,thead,time,title,tr,ul,var,video,area,base,bdo,canvas,caption,col,colgroup,command,datalist,dd,dl,dt,embed,iframe,keygen,map,menu,object,output,param,progress,rp,rt,ruby".split(",");
        var retval = {
                //Adds all arguments to a document fragment.
                $fragment: function (arr) { return unfoldArgumentInto.apply(document.createDocumentFragment(), arr); },
                $elem: forElem
        };
        for (var elI = 0; elI < elNames.length; elI++)
                retval[elNames[elI]] = forElem(elNames[elI]);
        //creates a document fragment; appends all arguments as content.
        return retval;
})();


</script>
<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js"></script>

<script id="template" type="text/x-handlebars-template"><div class="Foo{{#if isSelected}} selected{{/if}}{{#if isActive}} selected{{/if}}">
    <label><input type="checkbox" checked="{{#if isSelected}}checked{{/if}}"></label>
    <button class="button" title="A title">The button text</button>
    <a href="{{href}}"><span class="lorem{{#ifGreaterThanOne total}} ipsum{{/ifGreaterThanOne}}">
        <span class="dolores" unselectable="on">{{text}}</span>
        {{#ifGreaterThanOne total}}
        <span class="total" unselectable="on">({{total}})</span>
        {{/ifGreaterThanOne}}
        {{#if yes}}
        <span class="yes">*</span>
        {{/if}}
        <span class="text" unselectable="on">
        {{#ifGreaterThanOne total}}{{text}}{{/ifGreaterThanOne}}
        </span>
        <time unselectable="on" title="{{displayDate}}">{{displayDate}}</time>
        <span class="preview" unselectable="on">{{preview}}</span>
    </a>
</div>
</script>

<script type="text/javascript">
"use strict";

var create = (function () {

var doc = document;

var directProperties = {
    'class': 'className',
    className: 'className',
    defaultValue: 'defaultValue',
    'for': 'htmlFor',
    html: 'innerHTML',
    text: 'textContent',
    value: 'value'
};

var booleanProperties = {
    checked: 1,
    defaultChecked: 1,
    disabled: 1,
    multiple: 1,
    selected: 1
};

var setProperty = function ( el, key, value ) {
    var prop = directProperties[ key ];
    if ( prop ) {
        el[ prop ] = ( value == null ? '' : '' + value );
    } else if ( booleanProperties[ key ] ) {
        el[ key ] = !!value;
    } else if ( value == null ) {
        el.removeAttribute( key );
    } else {
        el.setAttribute( key, '' + value );
    }
};

var appendChildren = function ( el, children ) {
    var i, l, node;
    for ( i = 0, l = children.length; i < l; i += 1 ) {
        node = children[i];
        if ( node ) {
            if ( node instanceof Array ) {
                appendChildren( el, node );
            } else {
                if ( typeof node === 'string' ) {
                    node = doc.createTextNode( node );
                }
                el.appendChild( node );
            }
        }
    }
};


var create = function ( tag, props, children ) {
    if ( props instanceof Array ) {
        children = props;
        props = null;
    }
   
    var parts, name, el,
        i, j, l, node, prop;
   
 
   
    el = doc.createElement( tag );
    if ( props ) {
        for ( prop in props ) {
            setProperty( el, prop, props[ prop ] );
        }
    }
    if ( children ) {
        appendChildren( el, children );
    }
    return el;
};

return create;

}() );

var data = {
    isSelected: true,
    isActive: false,
    href: 'http://www.google.com',
    total: 4,
    displayDate: '28th December 2011',
    text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
    preview: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
};


var genDOMWithSugar = function ( data, target ) {
    var el = create;
    var newEl=(
    el( 'div', {
        className: 'Foo' +
            ( data.isSelected ? ' selected' : '' ) +
            ( data.isActive ? ' active' : '' )
    }, [
        el( 'label', [
            el( 'input', {
                type: 'checkbox',
                checked: data.isSelected ? 'checked': ''
            })
        ]),
        el( 'button', {
            className:'button',
            title: 'A title',
            text: 'The button text'
        }),
        el( 'a', {
            href: data.href
        }, [
            el( 'span', {
                className: 'lorem' +
                    ( data.total > 1 ? ' ipsum' : '' )
            }, [
                el( 'span', {
                    className:'dolores',
                    unselectable: 'on'
                }, [
                    data.text
                ]),
                data.total > 1 ? el( 'span', {
                    className:'total',
                    unselectable: 'on',
                    text: '(' + data.total + ')'
                }) : null
            ]),
            data.yes ? el( 'span', {
                className:'yes',text: '*'
            }) : null,
            el( 'span', {
                className:'text',unselectable: 'on'
            }, [
                data.total > 1 ? data.text : null
            ]),
            el( 'time', {
                unselectable: 'on',
                text: data.displayDate,
                title: data.displayDate
            }),
            el( 'span', {
                className:'preview',unselectable: 'on',
                text: data.preview
            })
        ])
    ] )
);
    if(target.firstChild) target.replaceChild(newEl,target.firstChild);
    else target.appendChild(newEl);
};



var genHtmlFactory = function (data, target) {
        "use strict";
        var _ = HtmlFactory;
        var content = _.
        div.attrs({
                'class': 'Foo' + (data.isSelected ? ' selected' : '') + (data.isActive ? ' active' : '')
        })([
            _.label(
                _.input.attrs({
                        type: 'checkbox',
                        checked: data.isSelected ? 'checked' : undefined
                })()
            ),
            _.button.attrs({
                'class': 'button',
                title: 'A title',
            })('The button text'),
            _.a.attrs({
                href: data.href
            })([
                                _.span.attrs({
                        'class': 'lorem' + (data.total > 1 ? ' ipsum' : '')
                })([
                    _.span.attrs({
                        'class': 'dolores',
                        unselectable: 'on'
                    })(data.text),
                    data.total > 1 ? _.span.attrs({
                        'class': 'total',
                        unselectable: 'on',
                    })('(' + data.total + ')') : undefined
                ]),
                data.yes ? _.span.attrs({
                    'class': 'yes'
                })('*') : undefined,
                _.span.attrs({
                    'class': 'text',
                    unselectable: 'on'
                })(data.total > 1 ? data.text : undefined),
                _.time.attrs({
                    unselectable: 'on',
                    title: data.displayDate
                })(data.displayDate),
                _.span.attrs({
                    'class': 'preview',
                    unselectable: 'on'
                })(data.preview)
            ])
    ]);
        if(target.firstChild) target.replaceChild(content,target.firstChild);
        else target.appendChild(content);
};


var genDOM = function ( data, target ) {
    var doc = document,
        div = doc.createElement( 'div' );
   
    div.className = 'Foo' +
        ( data.isSelected ? ' selected' : '' ) +
        ( data.isActive ? ' active' : '' );
   
    var label = doc.createElement( 'label' ),
        input = doc.createElement( 'input' );
    input.setAttribute( 'type', 'checkbox' );
    input.checked = !!data.isSelected;
    label.appendChild( input );
    div.appendChild( label );
   
    var button = doc.createElement( 'button' );
    button.className = 'button';
    button.setAttribute( 'title', 'A title' );
    button.textContent = 'The button text';
    div.appendChild( button );
   
    var a = doc.createElement( 'a' );
    a.setAttribute( 'href', data.href );
   
    var span = doc.createElement( 'span' );
    span.className = 'lorem' +
        ( data.total > 1 ? ' ipsum' : '' );
   
    var span2 = doc.createElement( 'span' );
    span2.className = 'dolores';
    span2.setAttribute( 'unselectable', 'on' );
    span2.appendChild( doc.createTextNode( data.text ) );
    span.appendChild( span2 );
   
    if ( data.total > 1 ) {
        span2 = doc.createElement( 'span' );
        span2.className = 'total';
        span2.setAttribute( 'unselectable', 'on' );
        span2.textContent = '(' + data.total + ')';
        span.appendChild( span2 );
    }
    a.appendChild( span );
    if ( data.yes ) {
        span = doc.createElement( 'span' );
        span.className = 'yes';
        span.textContent = '*';
        a.appendChild( span );
    }
   
    span = doc.createElement( 'span' );
    span.className = 'text';
    span.setAttribute( 'unselectable', 'on' );
    if ( data.total > 1 ) {
        span.appendChild( doc.createTextNode(  data.text ) );
    }
    a.appendChild( span );
   
    var time = doc.createElement( 'time' );
    time.setAttribute( 'unselectable', 'on' );
    time.textContent = data.displayDate;
    time.setAttribute( 'title', data.displayDate );
    a.appendChild( time );
   
    span = doc.createElement( 'span' );
    span.className = 'preview';
    span.setAttribute( 'unselectable', 'on' );
    span.textContent = data.preview;
    a.appendChild( span );
   
    div.appendChild( a );

    if(target.firstChild) target.replaceChild(div,target.firstChild);
    else target.appendChild(div);
};

var genDOMWithInnerHTML = function ( data,target ) {
    target.innerHTML = '<div class="Foo' +
            (data.isSelected ? ' selected' : '') +
            (data.isActive ? ' active' : '') + '">' +
        '<label><input type="checkbox" checked="' +
        (data.isSelected ? 'checked': '') + '"></label>' +
        '<button class="button" title="A title">The button text</button>' +
        '<a href="' + data.href + '"><span class="lorem' +
            ( data.total > 1 ? ' ipsum' : '' ) +
            '"><span class="dolores" unselectable="on">' + data.text +
            '</span>' + ( data.total > 1 ?
                '<span class="total" unselectable="on">(' + data.total + ')</span>' :
                '') +
            '</span>' + (data.yes ? '<span class="yes">*</span>' : '') +
            '<span class="text" unselectable="on">' +
            (data.total > 1 ? data.text : null) +
            '</span>' +
            '<time unselectable="on" title="' + data.displayDate + '">' +
            data.displayDate +
            '</time><span class="preview" unselectable="on">' + data.preview +
            '</span></a></div>';
};

Handlebars.registerHelper( 'ifGreaterThanOne', function( number, options ) {
    if ( number > 1 ) { return options.fn( this ); }
});

var template = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
  helpers = helpers || Handlebars.helpers;
  var buffer = "", stack1, stack2, foundHelper, tmp1, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression, blockHelperMissing=helpers.blockHelperMissing;

function program1(depth0,data) {
 
 
  return " selected";}

function program3(depth0,data) {
 
 
  return " selected";}

function program5(depth0,data) {
 
 
  return "checked";}

function program7(depth0,data) {
 
 
  return " ipsum";}

function program9(depth0,data) {
 
  var buffer = "", stack1;
  buffer += "\n        <span class=\"total\" unselectable=\"on\">(";
  foundHelper = helpers.total;
  stack1 = foundHelper || depth0.total;
  if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
  else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "total", { hash: {} }); }
  buffer += escapeExpression(stack1) + ")</span>\n        ";
  return buffer;}

function program11(depth0,data) {
 
 
  return "\n        <span class=\"yes\">*</span>\n        ";}

function program13(depth0,data) {
 
  var stack1;
  foundHelper = helpers.text;
  stack1 = foundHelper || depth0.text;
  if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
  else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "text", { hash: {} }); }
  return escapeExpression(stack1);}

  buffer += "<div class=\"Foo";
  foundHelper = helpers.isSelected;
  stack1 = foundHelper || depth0.isSelected;
  stack2 = helpers['if'];
  tmp1 = self.program(1, program1, data);
  tmp1.hash = {};
  tmp1.fn = tmp1;
  tmp1.inverse = self.noop;
  stack1 = stack2.call(depth0, stack1, tmp1);
  if(stack1 || stack1 === 0) { buffer += stack1; }
  foundHelper = helpers.isActive;
  stack1 = foundHelper || depth0.isActive;
  stack2 = helpers['if'];
  tmp1 = self.program(3, program3, data);
  tmp1.hash = {};
  tmp1.fn = tmp1;
  tmp1.inverse = self.noop;
  stack1 = stack2.call(depth0, stack1, tmp1);
  if(stack1 || stack1 === 0) { buffer += stack1; }
  buffer += "\">\n    <label><input type=\"checkbox\" checked=\"";
  foundHelper = helpers.isSelected;
  stack1 = foundHelper || depth0.isSelected;
  stack2 = helpers['if'];
  tmp1 = self.program(5, program5, data);
  tmp1.hash = {};
  tmp1.fn = tmp1;
  tmp1.inverse = self.noop;
  stack1 = stack2.call(depth0, stack1, tmp1);
  if(stack1 || stack1 === 0) { buffer += stack1; }
  buffer += "\"></label>\n    <button class=\"button\" title=\"A title\">The button text</button>\n    <a href=\"";
  foundHelper = helpers.href;
  stack1 = foundHelper || depth0.href;
  if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
  else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "href", { hash: {} }); }
  buffer += escapeExpression(stack1) + "\"><span class=\"lorem";
  foundHelper = helpers.total;
  stack1 = foundHelper || depth0.total;
  foundHelper = helpers.ifGreaterThanOne;
  stack2 = foundHelper || depth0.ifGreaterThanOne;
  tmp1 = self.program(7, program7, data);
  tmp1.hash = {};
  tmp1.fn = tmp1;
  tmp1.inverse = self.noop;
  if(foundHelper && typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, tmp1); }
  else { stack1 = blockHelperMissing.call(depth0, stack2, stack1, tmp1); }
  if(stack1 || stack1 === 0) { buffer += stack1; }
  buffer += "\">\n        <span class=\"dolores\" unselectable=\"on\">";
  foundHelper = helpers.text;
  stack1 = foundHelper || depth0.text;
  if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
  else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "text", { hash: {} }); }
  buffer += escapeExpression(stack1) + "</span>\n        ";
  foundHelper = helpers.total;
  stack1 = foundHelper || depth0.total;
  foundHelper = helpers.ifGreaterThanOne;
  stack2 = foundHelper || depth0.ifGreaterThanOne;
  tmp1 = self.program(9, program9, data);
  tmp1.hash = {};
  tmp1.fn = tmp1;
  tmp1.inverse = self.noop;
  if(foundHelper && typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, tmp1); }
  else { stack1 = blockHelperMissing.call(depth0, stack2, stack1, tmp1); }
  if(stack1 || stack1 === 0) { buffer += stack1; }
  buffer += "\n        ";
  foundHelper = helpers.yes;
  stack1 = foundHelper || depth0.yes;
  stack2 = helpers['if'];
  tmp1 = self.program(11, program11, data);
  tmp1.hash = {};
  tmp1.fn = tmp1;
  tmp1.inverse = self.noop;
  stack1 = stack2.call(depth0, stack1, tmp1);
  if(stack1 || stack1 === 0) { buffer += stack1; }
  buffer += "\n        <span class=\"text\" unselectable=\"on\">\n        ";
  foundHelper = helpers.total;
  stack1 = foundHelper || depth0.total;
  foundHelper = helpers.ifGreaterThanOne;
  stack2 = foundHelper || depth0.ifGreaterThanOne;
  tmp1 = self.program(13, program13, data);
  tmp1.hash = {};
  tmp1.fn = tmp1;
  tmp1.inverse = self.noop;
  if(foundHelper && typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, tmp1); }
  else { stack1 = blockHelperMissing.call(depth0, stack2, stack1, tmp1); }
  if(stack1 || stack1 === 0) { buffer += stack1; }
  buffer += "\n        </span>\n        <time unselectable=\"on\" title=\"";
  foundHelper = helpers.displayDate;
  stack1 = foundHelper || depth0.displayDate;
  if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
  else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "displayDate", { hash: {} }); }
  buffer += escapeExpression(stack1) + "\">";
  foundHelper = helpers.displayDate;
  stack1 = foundHelper || depth0.displayDate;
  if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
  else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "displayDate", { hash: {} }); }
  buffer += escapeExpression(stack1) + "</time>\n        <span class=\"preview\" unselectable=\"on\">";
  foundHelper = helpers.preview;
  stack1 = foundHelper || depth0.preview;
  if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
  else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "preview", { hash: {} }); }
  buffer += escapeExpression(stack1) + "</span>\n    </a>\n</div>\n";
  return buffer;});


var genHandlebarsTemplate = function ( data,target ) {
    target.innerHTML = template( data );
};
</script>
<script>
Benchmark.prototype.setup = function() {
    var targetDivNode = document.getElementById("targetEl");
    while (targetDivNode.hasChildNodes()) targetDivNode.removeChild(targetDivNode.lastChild);
   
   
   
};
</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
genDOMWithInnerHTML( data,targetDivNode  );
pending…
DOM
genDOM( data ,targetDivNode );
pending…
Sugared DOM
genDOMWithSugar( data ,targetDivNode  );
pending…
HtmlFactory
genHtmlFactory( data ,targetDivNode  );
pending…
Handlebars template
genHandlebarsTemplate( data ,targetDivNode  );
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