Created
January 21, 2018 15:33
-
-
Save matsnow/43af654fbd2dd8a72f76cbc7ef0193f9 to your computer and use it in GitHub Desktop.
Compare the throughput of Array.forEach and Array.map
This file contains 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 { 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