DEV Community

Discussion on: 1 Simple Trick to Boost Performance Using Reduce

Collapse
 
chochos profile image
Enrique Zamudio

If you filter first (as you should always do, when possible) then map iterates over a smaller array.

Others have already mentioned readability. But composition is also important: sometimes you already have the mapping and filtering functions somewhere and they are used in different contexts, so you just pass them to map and filter. Of course you can still implement a reduce that calls the mapping and filtering functions, but we go back to readability.
This seems like a useful trick when you need to filter and map over enormous arrays, but as a general guideline I would keep the mapping and filtering functions separate for readability and comparability (if that's even a word).
Maybe some day Javascript will have lazily evaluated streams and then this discussion will be moot.