DEV Community

loading...

Discussion on: Don’t pay the for-loop tax

Collapse
mdg583 profile image
Matt

Have to say I disagree. I think this is a matter of style.

  • The whole purpose of a function (typically) is to 'abstract out' a collection of logic into a more general, broad operation. Like your first example, if you want a function to sum elements in an array but the language doesn't have that function, you write it. Whether you use a loop at that point or use a function that abstracts out the logic of a loop is your choice, at the end of the day your abstracting the entire job of computing the sum or elements into a single function anyway.
  • I like working with C and thinking about a program closer to the way that it is actually being run on a lower level. When I see the iterative sum function in your first example, I tend to actually conceptualize a block of memory and think of the need to iterate over that memory in order to make use of each piece of memory. Seeing something like "array.reduce" means I need to go off to consult an api and figure out what this function is and how to use it, and there could be nuances of the function that I want to know about - like if I had wanted something that iterates over an array but can also increase the size of the array in the process of iteration or something like that. With a loop, the possibilities and limitations are more obvious.
  • that said there can be something nice about not using iterators. I remember this from working with matlab, where you can write computations in terms of matrices, which naively looked like they would be really inefficient computations, but which matlab could somehow work with to compute quickly.