Skip to content

Instantly share code, notes, and snippets.

@matyasfodor
Created January 31, 2018 15:08
Show Gist options
  • Save matyasfodor/a2c30ebcc5f526517f88c415459c9e4c to your computer and use it in GitHub Desktop.
Save matyasfodor/a2c30ebcc5f526517f88c415459c9e4c to your computer and use it in GitHub Desktop.
Comparison of forEach and map
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