Skip to content

re: Why you should use reduce instead of loops -- Part I VIEW POST

re: The big performance difference is because you basically compared for in loop with for of. I came up with another performance test set here: jsperf....

Hi Krzysztof Miemiec, thanks for your feedback, you are correct! I've made the correction to the post. The results are comparable. We can also create a reduce function that utilize better algorithms depending on the data type given. For example

function reduceImproved(
  ) {
    let acc = initialValue
    if (data.length) {
      for ( let count = 0, length = data.length; count < length; count++ ) {
        acc = reducer( acc, data[count], count )
    } else {
      let count = 0
      for ( const item of data ) {
        acc = reducer( acc, item, count++ )
    return acc

I've not tested this but the idea is that one could create a general purpose reduce for iterators in general while maintaining performance. As mentioned in the article, the reducers themselves can also be improved. We can even reach for WebAssembly, were applicable, and improve our application without having to change a single line of code.

In future parts on this topic, I will go on to discuss how our iterable reduce can be enhanced to handle asynchronous data, such as streams, with ease!

Thanks again for your corrections and feedback!


I think that your utility may end up looking like rxjs 😉 Nevertheless, I get the point that internally optimized, general-purpose reducers can be a cool internal utility for executing loops in a clean & easy-to-read manner. As a performance freak, I'm quite surprised that this approach is that performant. I'll try to use something similar in one of the products I'm working on! Thanks for the article 💪🏻

code of conduct - report abuse