Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compare the throughput of Array.forEach and Array.map
const { performance } = require('perf_hooks');
const times = 1000;
const formatter = (num) => Math.floor(num * 100) / 100;
const benchmark = (fn) => {
performance.mark('A');
fn.call()
performance.mark('B');
performance.measure('A to B', 'A', 'B');
const measure = performance.getEntriesByName('A to B')[0];
performance.clearMeasures();
return measure.duration;
};
const benchmarks = (fn) => {
let min = 999, max = 0, sum = 0;
Array(times).fill(0).map(() => benchmark(fn)).map((ms) => {
sum += ms;
max = (max < ms) ? ms : max;
min = (min > ms) ? ms : min;
});
console.log(`max = ${formatter(max)}ms : min = ${formatter(min)}ms : ave = ${formatter(sum / times)}ms`);
};
const arr1 = Array(1000000).fill(1);
console.log('forEach');
benchmarks(() => {
const arr2 = [];
arr1.forEach((elem) => {
arr2.push(`${elem} hoge`);
});
});
console.log();
console.log('map');
benchmarks(() => {
const arr2 = arr1.map((elem) => {`${elem} hoge`});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.