Last active
July 3, 2024 07:04
-
-
Save sairion/b081e019905c9ca1452ee8236527ae13 to your computer and use it in GitHub Desktop.
https://x.com/minsangk/status/1808327029240291465 (snapped from https://github.com/wickedev/fp-benchmark)
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
console.clear(); | |
async function bootstrap() { | |
const N = 100_000_000; | |
console.log(`N: ${N}`); | |
console.time("init numbers"); | |
const rangeLen = (b) => Array.from({ length: b }).map((_, i) => i) | |
const numbers = rangeLen(N).map(() => Math.floor(Math.random() * 10)); | |
const square = (x) => x * x; | |
const isEven = (x) => x % 2 === 0; | |
const add = (acc, x) => acc + x; | |
console.timeEnd("init numbers");; | |
console.log(""); | |
await (async () => { | |
const start = performance.now() | |
let sumOfSquares = 0; | |
for (let i = 0; i < numbers.length; i++) { | |
if (numbers[i] % 2 === 0) { | |
sumOfSquares += numbers[i] * numbers[i]; | |
} | |
} | |
console.log(`for: ${performance.now() - start}`); | |
console.log(sumOfSquares) | |
})(); | |
console.log(""); | |
await (async () => { | |
const start = performance.now() | |
let sumOfSquares = 0; | |
for (let number of numbers) { | |
if (number % 2 === 0) { | |
sumOfSquares += number * number; | |
} | |
} | |
console.log(`for-of: ${performance.now() - start}`); | |
console.log(sumOfSquares) | |
})(); | |
console.log(""); | |
await (async () => { | |
const start = performance.now() | |
const sumOfSquares = numbers | |
.filter(isEven) | |
.map(square) | |
.reduce(add, 0); | |
console.log(`raw-map-filter-reduce: ${performance.now() - start}`); | |
console.log(sumOfSquares) | |
})(); | |
console.log(""); | |
await (async () => { | |
const start = performance.now() | |
const sumOfSquares = numbers.reduce((a, b) => isEven(b) ? add(a, square(b)) : a, 0) | |
console.log(`reduce: ${performance.now() - start}`); | |
console.log(sumOfSquares) | |
})(); | |
console.log(""); | |
} | |
bootstrap().finally(async () => { }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment