Skip to content

Instantly share code, notes, and snippets.

@ricardobeat
Created September 10, 2018 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardobeat/477934e079dfebf55977d181ede1029d to your computer and use it in GitHub Desktop.
Save ricardobeat/477934e079dfebf55977d181ede1029d to your computer and use it in GitHub Desktop.
Inline event attributes benchmark
<!doctype html>
<body></body>
<script>
const events = [
'click',
'input',
'change',
'mouseenter',
'mouseleave',
'mousemove',
'mousedown',
'mouseup',
'wheel',
'scroll',
'select',
'focus',
'blur',
'reset',
'submit',
'keydown',
'keypress',
'keyup'
]
const selectors = events.map(e => `[on\\:${e}]`).join()
const makeElement = () => {
var ev = 'on:' + events[Math.random() * events.length | 0]
var tag = ['button', 'textarea', 'div', 'a'][Math.random() * 4 | 0]
var div = document.createElement('div');
div.innerHTML = `<${tag} ${ev}="foo"></${tag}>`;
return div.firstChild;
}
const movingAverage = (p,c,i) => p+(c-p)/(i+1);
const benchOne = (name, N, fn) => {
let times = [];
for (let i=0; i < N; i++) {
let start = performance.now()
fn()
times.push(performance.now() - start);
}
console.log(`${name}: ${times.reduce(movingAverage, 0).toFixed(2)}ms`);
}
const benchmark = (els = 10) => {
const N = 100;
console.group(`${els} elements:`)
document.body.innerHTML = ''
for (let i = 0; i < els; i++) {
document.body.appendChild(makeElement())
}
benchOne('querySelector', N, () => {
var nodes = document.querySelectorAll(selectors);
for (let j = 0; j < nodes.length; j++) {
nodes[j].getAttribute('on:click')
}
if (nodes.length !== els) throw new Error(`Node count doesn't match: ${els} x ${nodes.length}`)
})
benchOne('getElementsByTagName', N, () => {
var nodes = document.getElementsByTagName('*');
var count = 0;
for (let j = 0; j < nodes.length; j++) {
node = nodes[j];
var attributes = node.attributes;
for (let k = 0, n = attributes.length; k < n; k++) {
attr = attributes[k];
if (attr.name.indexOf('on:') === 0) {
count++;
}
}
}
if (count !== els) throw new Error(`Node count doesn't match: ${els} x ${nodes.length}`)
})
console.groupEnd()
}
benchmark(1);
benchmark(100);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment