For loops: jquery.appendTo() vs. array push/join

Benchmark created by Mike Harsh on


Description

Tests performance of appending DOM multiple times in each for loop VS. adding to an array in each loop and appending array to DOM once following the loop.

Preparation HTML

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

<div id="testContainer" style="display:none;">
    <div id="test1"></div>
    <div id="test2"></div>
</div>
<script>
  var t1 = $("#test1");
  var t2 = $("#test2");
  var t2a = [];
  var loops = 20;
  var testLoop = 0;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery appendTo
for (var i=0, len=loops; i<loops; i++) {
  var n = "t1_"+i+"_"+testLoop; 
  $("<div id='"+n+"'></div>").appendTo(t1);
  $("<h2>Section head</h2>").appendTo("#"+n);
  $("<p>Bodycopy</p>").appendTo("#"+n);
}
testLoop++;
ready
Array push/join
t2a = [];
for (var i=0, len=loops; i<loops; i++) {
  var n = "t2_"+i+"_"+testLoop; 
  t2a.push("<div id='"+n+"'>");
  t2a.push("<h2>Section head</h2>");
  t2a.push("<p>Bodycopy</p>");
  t2a.push("</div>");
}
// join elements in array and append as nodes to the DOM
$(t2a.join("\n")).appendTo(t2);
testLoop++;
ready

Revisions

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