A short story about Alice.
- She needs to do some side-effects (e.g. call an API, mutate an external object) with every item in the array
- She doesn’t need to mutate the original array
- There is no need for a new result array
. However, Alice is not the senior developer in the team and during a code review of her task, the local “senior” developer starts a crusade sworn to never ever use
again because it is the slowest of all loops.
map vs forEach speed
search on Google:
with additional functionality. I had to investigate.
Returning to my CodePen example, on average these are the results I received:
Chrome Version 77.0.3865.90 (Official Build) (64-bit)
Safari Version 13.0.1 (14608.2.11.1.11)
is made to mimic what
does. In other words, an improper use of functions and a generalisation of results.
Returning to Alice, she won the holy war against the “senior” developer and forEach was used in her case.
However, this is not unusual for teams to get stuck discussing topics they are frankly yet unqualified to discuss. I say unqualified because even if many of us would like to say we know our languages from A to Z, we still often have not enough data to back up our claims. Or even worse, we have no data at all.
Such scenarios are dangerous because more experienced developers pass their opinions to less experienced (or simply gullible) developers. All of this increases the lifespan of an opinion regardless whether it’s wrong or right.
Be sceptical. It’s never too early to question things. In fact, in a company, that’s what good management wants.
By the way, did you notice that a simple for loop was way slower than any of the other loops? ~90–95% slower to be exact. Weird, huh? I yet haven’t managed to understand the reason for this, but I suspect that I accidentally created a bias example towards a simple for loop. Now go out and scream from the rooftops:
For loop is dead. Long live for loop.
In conclusion, what I’m getting at is this:
- Test your claims
- Test your data
- Test what others claim
- Test the data and results of others
- Different contexts create different results. These results, if generalised, might create a bias.
Array.map + Array.filter
was used instead of a
Instead it’s more important to focus on having guidelines instead of waging war against your teammates.
“Understanding others needs to start on an individual level — understanding yourself.
Knowing how easy it is to make these kinds of mistakesallows us to be more compassionate when seeing others encounter the same issues”
P.S. This article expresses no preference towards the functions, methods used here. It is purely about human bias and why it’s dangerous.
P.S.S. If you see a clear bias in my CodePen example or that I’m wrong in something, I’d be happy to hear why. Also, that would only further prove my point of how easy bias occurs.