Created
May 25, 2023 08:01
-
-
Save akx/76818fb782a232b5e08eae785cb3ee97 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
</head> | |
<body> | |
<script> | |
function sleep(ms = 0) { | |
return new Promise(r => setTimeout(r, ms)); | |
} | |
function toggle_class_orig(element, name, toggle) { | |
element.classList[toggle ? 'add' : 'remove'](name); | |
} | |
function toggle_class_toggle(element, name, toggle) { | |
element.classList.toggle(name, !!toggle); | |
} | |
function toggle_class_if(element, name, toggle) { | |
if (toggle) { | |
element.classList.add(name); | |
} else { | |
element.classList.remove(name); | |
} | |
} | |
function toggle_class_ternary(element, name, toggle) { | |
toggle ? element.classList.add(name) : element.classList.remove(name); | |
} | |
function benchmark_fn(fn) { | |
var element = document.body; | |
var start = Date.now(); | |
for (var i = 0; i < 2 ** 22; i++) { | |
fn(element, 'class', true); | |
fn(element, 'class', false); | |
} | |
var end = Date.now(); | |
let t = end - start; | |
console.log(fn, t); | |
return t; | |
} | |
async function benchmark(b) { | |
b.disabled = true; | |
b.innerText = ""; | |
for (const fn of [toggle_class_orig, toggle_class_toggle, toggle_class_if, toggle_class_ternary]) { | |
b.innerText += `${fn.name} ...`; | |
await sleep(100); | |
const t = benchmark_fn(fn); | |
b.innerText += ` ${t}ms\n`; | |
await sleep(100); | |
} | |
b.disabled = false; | |
b.innerText = "Done"; | |
} | |
</script> | |
<button onclick="benchmark(this)">Benchmark</button> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment