Skip to content

Instantly share code, notes, and snippets.

@lukasz-zak
Last active May 1, 2022 22:35
Show Gist options
  • Save lukasz-zak/48486ab35f7ea4bc1ba4 to your computer and use it in GitHub Desktop.
Save lukasz-zak/48486ab35f7ea4bc1ba4 to your computer and use it in GitHub Desktop.
createElement vs createDocumentFragment
/**
* Code which I test on twitter.com
* Both tests were runing in Chrome 35.x dev tools
*
* This test just gets all a tags from html and read their content
* and then write it on end of document (body element)
*
**/
console.time('testCreateElem');
elemA = document.getElementsByTagName('a');
body = document.getElementsByTagName('body')[0];
for(var i = 0; i < elemA.length; i++){
var span = document.createElement('span');
span.textContent = elemA[i].textContent;
body.appendChild(span);
}
console.timeEnd('testCreateElem');
// Result 36ms
//=======================================
console.time('testDocumentFragment');
elemA = document.getElementsByTagName('a');
body = document.getElementsByTagName('body')[0];
fragment = document.createDocumentFragment();
for(var i = 0; i < elemA.length; i++){
var span = document.createElement('span');
span.textContent = elemA[i].textContent;
fragment.appendChild(span);
}
body.appendChild(fragment);
console.timeEnd('testDocumentFragment');
// Result 7ms
@NehaChaudhary311
Copy link

Nice

@garretmh
Copy link

garretmh commented May 1, 2022

Minimizing the number of DOM updates makes a big difference even without a Fragment:

console.time('testCreateElem');

elemA = document.getElementsByTagName('a');
body = document.getElementsByTagName('body')[0];
list = []

for(var i = 0; i < elemA.length; i++){
  var span = document.createElement('span');
  span.textContent = elemA[i].textContent;
  list.push(span);
}
body.append(...list)
console.timeEnd('testCreateElem');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment