Skip to content

Instantly share code, notes, and snippets.

@oliverfernandez
Created May 21, 2013 11:31
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save oliverfernandez/5619180 to your computer and use it in GitHub Desktop.
Save oliverfernandez/5619180 to your computer and use it in GitHub Desktop.
The operation consists to append 12 nodes to an existing parent node with 1000 children Three ways to do it: 1. Use parentNode.innerHTML += 2. User parentNode.innerHTML = 3. Use a parentNode.appendChild inside a loop. The method with the best performance is the last one. The last method doesn't need to read the current DOM or parse it.
var mainNodeInner = document.createElement('div'),
mainNodeInnerPlus = document.createElement('div'),
mainNodeAppend = document.createElement('div'),
sampleHTML = '<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>',
testHTML = '',
numSamples = 1000,
before = null,
after = null;
//SET UP
for (i = 0; i < numSamples; i++) {
testHTML += sampleHTML;
}
//INNER HTML +=
mainNodeInnerPlus.innerHTML = testHTML;
before = new Date().getTime();
mainNodeInnerPlus.innerHTML += sampleHTML;
after = new Date().getTime();
console.log("TIME INNER HTML +=: " + (after - before) + " ms");
console.log("Num childs after: " + mainNodeInnerPlus.childElementCount);
console.log(' ');
//INNER HTML =
var allHTML = testHTML + sampleHTML;
before = new Date().getTime();
mainNodeInner.innerHTML = allHTML;
after = new Date().getTime();
console.log("TIME INNER HTML =: " + (after - before) + " ms");
console.log("Num childs after: " + mainNodeInner.childElementCount);
console.log(' ');
//APPEND CHILD
mainNodeAppend.innerHTML = testHTML;
before = new Date().getTime();
var sampleNode = document.createElement('div');
sampleNode.innerHTML = sampleHTML;
while(sampleNode.hasChildNodes()) {
mainNodeAppend.appendChild(sampleNode.firstChild);
}
after = new Date().getTime();
console.log("TIME APPEND CHILD: " + (after - before) + " ms");
console.log("Num childs after: " + mainNodeAppend.childElementCount);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment