Does using a document fragment really improve performance?

Document Fragment is much faster when it is used to insert a set of elements in multiple places. Most answers here point out its un-utility, but this is to demonstrate its strength.

Lets take an example.

Say we need to append 20 divs in 10 elements with class container.

Without:

var elements = [];
for(var i=20; i--;) elements.push(document.createElement("div"));

var e = document.getElementsByClassName("container");
for(var i=e.length; i--;) {
  for(var j=20; j--;) e[i].appendChild(elements[j].cloneNode(true));
}

With:

var frag = document.createDocumentFragment();
for(var i=20; i--;) frag.appendChild(document.createElement("div"));

var e = document.getElementsByClassName("container");
for(var i=e.length; i--;) e[i].appendChild(frag.cloneNode(true));

For me using a document fragment turns out to be 16 times faster on Chrome 48.

Test on JsPerf

Leave a Comment

tech