Skip to content

Instantly share code, notes, and snippets.

@jesusgoku
Created July 25, 2024 20:37
Show Gist options
  • Save jesusgoku/87d5eb7b0c15350893cfe3f17ae991d4 to your computer and use it in GitHub Desktop.
Save jesusgoku/87d5eb7b0c15350893cfe3f17ae991d4 to your computer and use it in GitHub Desktop.
Array `.map()` vs `.reduce()`
const size = 250_000;
const input = new Array(size).fill(undefined).map((_, index) => index);
[
{
name: '.map()',
fn: () => {
input.map((e) => e * 2);
}
},
{
name: '.reduce() and .push()',
fn: () => {
input.reduce((acc, e) => { acc.push(e * 2); return acc; }, new Array());
}
},
{
name: '.reduce() and new Array()',
fn: () => {
input.reduce((acc, e, index) => { acc[index] = e * 2; return acc; }, new Array(input.length));
}
},
].forEach(({ name, fn }) => {
const iterations = 2_000;
console.time(name);
for (let i = 0; i < iterations; ++i) {
fn();
}
console.timeEnd(name);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment