Skip to content

Instantly share code, notes, and snippets.

@matsnow
Created January 21, 2018 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsnow/43af654fbd2dd8a72f76cbc7ef0193f9 to your computer and use it in GitHub Desktop.
Save matsnow/43af654fbd2dd8a72f76cbc7ef0193f9 to your computer and use it in GitHub Desktop.
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