Last active
May 1, 2022 22:35
-
-
Save lukasz-zak/48486ab35f7ea4bc1ba4 to your computer and use it in GitHub Desktop.
createElement vs createDocumentFragment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 |
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
Nice