append vs. innerHTML vs. fragment

JavaScript performance comparison

Revision 3 of this test case created by Lee Brimelow

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var s = '<div id="response" class="quiet-scrollbars"><div id="tools"><a href="#" id="addButt"></a><a href="#" id="horzButt"></a><div class="divider"></div><div id="layoutText">LAYOUT</div><a href="#" class="vert-active" id="vertButt"></a><a href="#" id="inspectButton"></a><div id="inspectText">Inspect</div><div class="presetPos" id="button">PRESETS</div></div><div id="track"></div><input type="range" min="0" id="slider">';
   
   
    var domArray = [{tag:"div",attr:{id:"response", class:"quiet-scrollbars"}, parent:-1},{tag:"div",attr:{id:"tools"}, parent:0},{tag:"a",attr:{id:"addButt", href:"#"}, parent:1},{tag:"a",attr:{id:"horzButt", href:"#"}, parent:1},{tag:"a",attr:{class:"divider"}, parent:1},{tag:"a",attr:{class:"divider"}, parent:1},{tag:"div",attr:{id:"layoutText"}, text:"LAYOUT", parent:1},{tag:"a",attr:{id:"vertButt",class:"vert-active"}, parent:1},{tag:"div",attr:{id:"track"}, parent:0},{tag:"input",attr:{id:"slider",type:"range",min:"0"}, parent:0}];
   
    var d = document.createElement('div');
    document.body.appendChild(d);
};

Benchmark.prototype.teardown = function() {
    document.body.removeChild(d);
};
</script>

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 append
$(d).append(s);
pending…
innerHTML
d.innerHTML = s;
pending…
my fragment method
var frag = document.createDocumentFragment();
var elements = [];

while(domArray.length) {
  var el = domArray.shift();
  var element = document.createElement(el.tag);
  for(var a in el.attr) {
    element.setAttribute(a, el.attr[a]);
  }
  if(el.text) {
    element.appendChild(document.createTextNode(el.text));
  }
  elements.push(element);
               
  if(el.parent == -1)
     frag.appendChild(element);
  else
     elements[el.parent].appendChild(element);
}
d.appendChild(frag);
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:

1 comment

mymyoux commented :

can't we imagine to have a function that takes html code and outputs your object format ? I think it will still far more powerful! And even better can't we override JQuery append method to use your fragment method and give a big boost to existing projects without rewriting anything!

Add a comment