Skip to content

Instantly share code, notes, and snippets.

@sairion
Last active July 3, 2024 07:04
Show Gist options
  • Save sairion/b081e019905c9ca1452ee8236527ae13 to your computer and use it in GitHub Desktop.
Save sairion/b081e019905c9ca1452ee8236527ae13 to your computer and use it in GitHub Desktop.
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