Skip to content

Instantly share code, notes, and snippets.

@AVGP
Last active February 14, 2017 14:57
Show Gist options
  • Save AVGP/c718c4232b1bef95d8e1ba14a0732bce to your computer and use it in GitHub Desktop.
Save AVGP/c718c4232b1bef95d8e1ba14a0732bce to your computer and use it in GitHub Desktop.
Measuring speed of operations that append to DOM
<!doctype html>
<html>
<body>
<div id="target"></div>
<template>
<ul>
<li><a>Item #0</a></li>
<li><a>Item #1</a></li>
<li><a>Item #2</a></li>
<li><a>Item #3</a></li>
<li><a>Item #4</a></li>
<li><a>Item #5</a></li>
<li><a>Item #6</a></li>
<li><a>Item #7</a></li>
<li><a>Item #8</a></li>
<li><a>Item #9</a></li>
</ul>
</template>
<script>
// Setup
var target = document.getElementById('target')
var tpl = document.querySelector('template')
var fragment = new DocumentFragment()
var list = document.createElement('ul')
for(var i=0; i<10; i++) {
var li = document.createElement('li'),
a = document.createElement('a')
a.textContent = 'Item #' + i
li.appendChild(a)
list.appendChild(li)
}
fragment.appendChild(list)
var contentString = '<ul>'
for(var i=0; i<10; i++) contentString += '<li><a>Item #' + i + '</a></li>'
contentString += '</ul>'
// Running the tests
window.onload = function() {
var tStart = performance.now()
for(var t=0; t<10000; t++) {
//runTest0() // 1717175ms
//runTest1() // 642ms
//runTest2() // 222ms
//runTest3() // 211ms
//runTest4() // 1272ms
//runTest5() // 380ms
}
console.log(performance.now() - tStart)
}
function runTest0() {
target.innerHTML += contentString
}
function runTest1() {
var list = document.createElement('ul')
for(var i=0; i<10; i++) {
var li = document.createElement('li'),
a = document.createElement('a')
a.textContent = 'Item #' + i
li.appendChild(a)
list.appendChild(li)
}
target.appendChild(list)
}
// Using a DocumentFragment
function runTest2() {
target.appendChild(document.importNode(fragment, true))
}
// Using a <template>
function runTest3() {
var clone = document.importNode(tpl.content, true)
target.appendChild(clone)
}
// Using createContextualFragment
function runTest4() {
var range = document.createRange();
range.selectNode(target);
var documentFragment = range.createContextualFragment(contentString);
document.body.appendChild(documentFragment);
}
// Using insertAdjacentHTML
function runTest5() {
target.insertAdjacentHTML('beforeend', contentString)
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment