jQuery append vs document.createElement

JavaScript performance comparison

Revision 2 of this test case created

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script>
  var toString = Object.prototype.toString;
 
  var each = function(obj, fn) {
    for (i in obj) {
      obj.hasOwnProperty(i) && fn(obj[i], i);
    }
  };
 
  var attrs = {
    id : 'sectionMenu',
    className : 'section'
  };
 
  var htmlStr = "<div id='container'><div id='first'><p>First paragraph</p><p>Second paragraph</p></div></div>";
 
  var htmlObj = {
    tag   : 'div',
    attrs : {
      id  : 'container'
    },
    contents : [{
      tag : 'div',
      attrs : {
        id : 'first'
      },
      contents : [{
        tag : 'p',
        contents : ['First paragraph']
      },{
        tag : 'p',
        contents : ['Second paragraph']
      }]
    }]
  };
 
  function template (obj) {
    var el = document.createElement(obj.tag);
    each(obj.attrs, function(val, key) {
      el[key] = val;
    });
    each(obj.contents, function(val, key) {
      el.appendChild(
        toString.call(val) == '[object Object]' ?
          template(val) :
          document.createTextNode(val)
      );
    });
    return el
  };
</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
jQuery
var el = document.createElement('div');
$('<div />').attr(attrs).appendTo(el);
 
pending…
jQuery multi-element append
var el = document.createElement('div');
$(htmlStr).appendTo(el);
pending…
native multi-element append
var el = document.createElement('div');
el.appendChild(template(htmlObj));
pending…
native innerHTML
var el = document.createElement('div');
el.innerHTML = htmlStr;
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