That's because speed isn't always top priority. Readability is very high on the list.
I would rather have a slightly slower .map or .filter in a chain than a harder to read nested for or while loop.
That's because speed isn't always top priority. Readability is very high on the list.
I would rather have a slightly slower .map or .filter in a chain than a harder to read nested for or while loop.
I often find map/reduce/filter easier to read when using named functions (or lazy data structures ) for intermediary results - depending on the language/runtime that might imply more allocations - or not.
Eg pseudocode:
Integers.filter(//non-obvious prime sieve).sum()
Vs
Primes = Integer.filter(//non-obvious prime sieve)
Primes.sum()
Or lifting the anonymous filter to primes()-filter:
Integers.primes().sum()
But I have seen "functional contraptions of horror" where those functions are both chained and nested which were completely undecipherable by mere humans.
And at least from my personal impression, people who are a fan of this type of functional style are also more likely to create such horrors (which they themselves of course find totally readable and superior to "unreadable" loops) - I suspect that there's often a bit of cargo-culting going on.
In the front-end we were making about 20 API calls to fetch data we probably don't need yet and the developer is like: the problem has to exist in the way we call them, time to optimise the loops!
You can make a similar function that changes the data in place and will be faster. But that comes with side effects which is not functional style.
Lodash is MUCH faster than native because it uses iterators so you aren't actually looping over and over.
We need builtin iterator versions of all these looped functions so it adds an implicit/explicit `.valueOf()` that calls the chain and allocates only one new array.
But it's not going to help all that much with this problem. The iterator protocol in JS involves an allocation for every individual value, and while in some cases that can be optimized out, it's pretty tricky to completely optimize.
It's always going to be difficult to beat a c-style for loop for performance.