Skip to content

Instantly share code, notes, and snippets.

@akx
Created May 25, 2023 08:01
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 akx/76818fb782a232b5e08eae785cb3ee97 to your computer and use it in GitHub Desktop.
Save akx/76818fb782a232b5e08eae785cb3ee97 to your computer and use it in GitHub Desktop.
<!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