Skip to content

Instantly share code, notes, and snippets.

@akx
Created May 25, 2023 05:32
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/97b237ae55589e7a166ab88c913b418e to your computer and use it in GitHub Desktop.
Save akx/97b237ae55589e7a166ab88c913b418e 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_1(element, name, toggle) {
element.classList[toggle ? 'add' : 'remove'](name);
}
function toggle_class_2(element, name, toggle) {
element.classList.toggle(name, !!toggle);
}
function benchmark_fn(fn) {
var element = document.body;
var start = Date.now();
for (var i = 0; i < 2 ** 20; i++) {
fn(element, 'class', true);
fn(element, 'class', false);
}
var end = Date.now();
console.log(fn, end - start);
}
async function benchmark(b) {
b.disabled = true;
b.innerText = "Running 1";
await sleep(0);
benchmark_fn(toggle_class_1);
b.innerText = "Running 2";
await sleep(0);
benchmark_fn(toggle_class_2);
await sleep(0);
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