Created
July 25, 2024 20:37
-
-
Save jesusgoku/87d5eb7b0c15350893cfe3f17ae991d4 to your computer and use it in GitHub Desktop.
Array `.map()` vs `.reduce()`
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
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