What is the Fastest Loop Type in JavaScript?

Kyle Le
Bits and Pieces
Published in
4 min readOct 11, 2022

--

Array Methods

JavaScript has multiple array methods built-in, almost all of them has loops inside them. First I will run the benchmark with 4 most common JS methods use for loop:

As you can see, forEach has the best performance out of the 4.

The reason why forEach is faster than map and filter is because it won’t return anything after it finished, just undefined but map and filter will return a new array. reduce is almost as fast as forEach, it is because it will return an initialValue ( if provided ) or return the value after calculation in the reducer function finished.

Built-in array methods are easy to use and have different use-cases, and the performance isn’t that significant when compare those function, they are beautiful to look at, to read, to write, and declarative. But when performance actually matters, other imperative approaches are multiple times faster.

For loops

First, take a look at this:

You can see that for loops are 3 time faster than array methods like forEach map and reduce. Upon receiving an array element, array methods execute a callback function for each element.

Now take an in-depth look in other traditional loops:

For loop, length uncached:

for (var x = 0; x < arr.length; x++) {
dosmth = arr[x];
}

For loop, length cached:

var len = arr.length;
for (var x = 0; x < len; x++) {
dosmth = arr[x];
}

For…of loop:

for (let val of arr) {
dosmth = val;
}

While loop, ++x:

var x = 0, l = arr.length;
while (x < l) {
dosmth = arr[x];
++x;
}

While loop, x++:

var x = 0, l = arr.length;
while (x < l) {
dosmth = arr[x];
x++;
}

Now I will run the benchmarks, the results are:

In common cases, for...of works great, but in large datasets, like the benchmark above, it’s relatively slower ( still faster than array methods )

Conclusion

If you prefer declarative programming, just go with array methods, they are easier to read, to write in general, and better in 99% cases in JavaScript.
But if you prefer performance, just use other imperative approaches.
In other words, just pick the loop type that suits your style and your situation.

Last Words

Although my content is free for everyone, but if you find this article helpful, you can buy me a coffee here

Build apps with reusable components like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

--

--

I’m a Software Engineer who loves to write. My content is based on what I've learned and experienced every day