Created
January 31, 2018 15:08
-
-
Save matyasfodor/a2c30ebcc5f526517f88c415459c9e4c to your computer and use it in GitHub Desktop.
Comparison of forEach and 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
function arr(n) { | |
return Array(n+1).join(1).split(''); | |
} | |
const a = arr(1000000) | |
a[100] = 2 | |
a[1000] = 2 | |
a[10000] = 2 | |
function timeit(label, cb) { | |
console.profile(label) | |
arr(100).forEach(() => { | |
cb(); | |
}) | |
console.profileEnd() | |
} | |
const case1 = () => { | |
a.map((val) => { | |
if (val === 2) { | |
console.log('it\'s 2 !'); | |
} | |
}) | |
} | |
const case2 = () => { | |
a.forEach((val) => { | |
if (val === 2) { | |
console.log('it\'s 2 !'); | |
} | |
}) | |
} | |
timeit('map', case1); | |
timeit('forEach', case2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment