DEV Community

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

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Do I like functional programming? Yes.
Is this particularly readable and self-explanatory, after all the optimizations? Meh.
Are there still pointless function calls and variable allocations? Basically.

const level2Sum = nums
  .reduce((prev, curr) => prev + 3 * curr ** 2, 0);

So if I will at all concern myself with optimizing this case I'll just go to the following, which doesn't at all lack readability:

let level3Sum = 0
for (const num of nums) {
  level3Sum += 3 * curr ** 2
}

But since I am in fact obsessed with using const so I know I'm not mutating this number later in the use site, I will extract this loop and assign to const:

/* IN THE ROOT SCOPE, NOT IN THE FUNCTION!!! */
const l3s = (nums: number[]) => {
  let sum = 0
  for (const num of nums) {
    sum += 3 * curr ** 2
  }
  return sum
}
/* elsewhere... */
const sum = l3s(nums)
Collapse
 
jay97 profile image
Jamal Al

While using map filter and reduce is great for readability. Using a for loop is the fastest of all. So if your looking to optimize as much as possible i would go with a for loop.

Collapse
 
zorqie profile image
I, Pavlov

In Chrome 71 level2Sum is still 88% slower than a C-style for loop.

jsperf.com/chained-maps-vs-for-loop

In Edge 42 the level3Sum is just as slow as the original chained maps.

Collapse
 
somedood profile image
Basti Ortiz

Oh, man. Indeed, that does look pretty messy. 😬