Created
January 13, 2023 21:06
-
-
Save caderek/58f4886091c013a7d8c1ac2d6817f9fe to your computer and use it in GitHub Desktop.
JS loops benchmark.
This file contains hidden or 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
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