DEV Community

Discussion on: Please don't "overchain" array methods

Collapse
 
dallgoot profile image
dallgoot

Very useful to remind people of that.
This is basic algorithm time complexity : with an array of N elements
one loop = O(N)
2 loop = O(N+N)
X loop = O(N*X)
So for an array of 10 elements and 4 ".map" the time to execution is 4 times what is needed.
And you need to add to that the time to push new values in the new arrayS.
I think a general rule can be "NEVER USE SAME ARRAY METHOD TWICE".
Also maybe always use "filter" before "map" ?
And i would also like to point that if for some people a 3 term operation is a problem of readability : god are people becoming this lazy ?

I too like readable code, but our primary goal is "efficiency".
Efficiency = performance and should ALWAYS take over what any idea of "beauty" someone may have.
I'm not talking about micro-optimizations but to avoid unnecessary operations.
First do the job in an efficient manner, then refactor to make it human readable as possible.
Sometimes complex things are complex to read.
We are not making art.

Collapse
 
somedood profile image
Basti Ortiz • Edited

I mean, one can't really say that those who disagree with this article are completely wrong. Readability really is an important aspect of writing code. Performant code means nothing if it is unreadable.

Also, yup, I definitely agree with using filter before map. That should honestly be a default for all JavaScript programmers.

Collapse
 
chuckwood profile image
Charles Wood • Edited

I like the perspective that we have to decide what we're optimizing: the writing, the execution, or the reading. Each has its place and tradeoffs.