Array.map() much slower than for loop
Henry Williams
Posted on April 28, 2019
I was working on some coding challenges when I got the sudden urge to test which approach was faster. For an input size of 1 million numbers, Array.map()
takes about 2,000ms, whereas a for
loop takes about 250ms. Any ideas why?
const INPUT_SIZE = 10 ** 7
const input = []
for(let i = 1; i <= INPUT_SIZE; i++) {
input.push(i)
}
const pow2 = value => value ** 2
console.time('map')
const mapResult = input.map(pow2)
console.timeEnd('map') // 1800-2000+ ms
console.time('loop')
const arrayResult = []
for(let i = 0; i < input.length; i++) {
arrayResult.push(pow2(input[i]))
}
console.timeEnd('loop') // 200-300ms
I always assumed Array.map()
would be faster since it's a built-in function, but it looks like I was wrong.
Test 2
So after thinking about this for a while, I decided to perform a more fair comparison: Array.forEach()
vs for
loop. The results were that Array.forEach()
is still slower, but not by as much as .map()
(550-700ms).
My guess is that .map()
performs some additional logic that slows it down significantly compared to a raw for
loop.
Edit: I'm aware that this isn't exactly a practical scenario as we shouldn't be processing this much data using Javascript. This scenario is for theoretical understanding and discussion.
Posted on April 28, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.