Skip to content

Instantly share code, notes, and snippets.

@TakayoshiKochi
Created December 2, 2016 08:22
Show Gist options
  • Save TakayoshiKochi/a4385510e4f483a02dd0027eb215cfe1 to your computer and use it in GitHub Desktop.
Save TakayoshiKochi/a4385510e4f483a02dd0027eb215cfe1 to your computer and use it in GitHub Desktop.
Benchmark for '>>>' and polyfill comparison (2)
<!DOCTYPE html>
<body>
<div id="root"></div>
</body>
<script>
'use strict';
if (window.testRunner) {
testRunner.dumpAsText();
}
let root = document.querySelector('#root');
// Build a DOM tree which is 4x4x4x32 = 2048 spans, 64 shadow roots
for (let i = 0; i < 4; ++i) {
let div1 = document.createElement('div');
let root1 = div1.attachShadow({mode: 'open'});
div1.classList.add('shadow');
for (let j = 0; j < 4; ++j) {
let div2 = document.createElement('div');
let root2 = div2.attachShadow({mode: 'open'});
div2.classList.add('shadow');
for (let k = 0; k < 4; ++k) {
let div3 = document.createElement('div');
let root3 = div3.attachShadow({mode: 'open'});
div3.classList.add('shadow');
for (let l = 0; l < 32; ++l) {
let div4 = document.createElement('span');
root3.appendChild(div4);
}
root2.appendChild(div3);
}
root1.appendChild(div2);
}
root.appendChild(div1);
}
function recursiveFindSpans(root, spans) {
Array.prototype.push.apply(spans, root.querySelectorAll('span'));
root.querySelectorAll('.shadow').forEach(e => {
spans = recursiveFindSpans(e.shadowRoot, spans);
});
return spans;
}
var start = window.performance.now();
for (let i = 0; i < 100; ++i) {
document.querySelectorAll('#root >>> span');
}
var end = window.performance.now();
console.log('Time :' + (end - start) + 'msec');
start = window.performance.now();
for (let i = 0; i < 100; ++i) {
recursiveFindSpans(document.querySelector('#root'), []);
}
end = window.performance.now();
console.log('Time :' + (end - start) + 'msec');
</script>
@TakayoshiKochi
Copy link
Author

This is a variant of https://gist.github.com/TakayoshiKochi/04fe33f40543ce07bdc53ecdfb6cc2e0
each shadow host has shadow class and thus can be found via querySelectorAll('.shadow').

The original JS emulation used querySelectorAll('*') to iterate all elements to find shadow hosts,
but this resulted in much faster execution.

CONSOLE MESSAGE: line 51: Time :29.155msec
CONSOLE MESSAGE: line 58: Time :122.11500000000001msec

(compared to the old code, emulation time reduced from ~900ms to ~120ms!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment