Skip to content

Instantly share code, notes, and snippets.

@Uvacoder
Forked from caderek/loops.bench.js
Created January 16, 2023 03:09
Show Gist options
  • Save Uvacoder/6a1a2618f29da8231ed35dbe65a84fd1 to your computer and use it in GitHub Desktop.
Save Uvacoder/6a1a2618f29da8231ed35dbe65a84fd1 to your computer and use it in GitHub Desktop.
JS loops benchmark.
import benny from "benny";
const data = Array.from({ length: 100_000 }, (_, i) => i);
let r1 = 0;
let r2 = 0;
let r3 = 0;
let r4 = 0;
let r5 = 0;
await benny.suite(
"Loop through array of 100k numbers",
benny.add("for", () => {
for (let i = 0; i < data.length; i++) {
r1 += data[i];
}
}),
benny.add("for..of", () => {
for (const item of data) {
r2 += item;
}
}),
benny.add("forEach", () => {
data.forEach((item) => {
r3 += item;
});
}),
benny.add("reduce", () => {
r4 += data.reduce((sum, item) => sum + item, 0);
}),
benny.add("while", () => {
let i = 0;
while (i < data.length) {
r5 += data[i];
i++;
}
}),
benny.cycle(),
benny.complete()
);
console.log({ r1, r2, r3, r4, r5 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment