Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save alexmaday/ae7859c6b290bdb2fe2859b4a3a53bf5 to your computer and use it in GitHub Desktop.

Select an option

Save alexmaday/ae7859c6b290bdb2fe2859b4a3a53bf5 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