Refactor use of forEach to for — provides 10x performance

Do you want to request a feature or report a bug?

As per @TheLarkInn tweet ( it has been brought to attention that there are some rather obvious performance gains (upwards of 10x) when using for over for-of and forEach

What is the current behavior?

Currently, forEach is being used throughout project.

If the current behavior is a bug, please provide the steps to reproduce.


What is the expected behavior?

Well, I expect it to be as fast and optimized as possible 🙂

If this is a feature request, what is motivation or use case for changing the behavior?

It is always better when things are faster!

Please mention other relevant information such as the browser version, Node.js version, webpack version and Operating System.

As per this sample gist

Local Results

  // v8 (Node.js 6.8.1)

for    : 1.113ms
for-of : 35.201ms
forEach: 24.478ms

Author: Fantashit

4 thoughts on “Refactor use of forEach to for — provides 10x performance

  1. I’m not sure this is a great idea. It can make things hard to read, really quickly. For example, changing

    this.watchings.forEach((watching) => watching.invalidate());


    const watchings = this.watchings;
    for (var i = 0, len = watchings.length; i < len; ++i) {
      const watching = watchings[i];

    is just ugly. And unless this.watchings is really big, it’s not going to save you any noticeable amount of time.

  2. I think this should be discussed as specific instances of forEach, not just as a whole. There are loops that iterate a few times and loops that iterate more than a few times. Going by the benchmarks in the opening post, the benefit for smaller loops (a few hundred iterations) would have to be measured in microseconds.

Comments are closed.