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
Top comments (2)
One thing should be mentioned about these different array loops: both
for-of
andforEach
will only iterate over existing entries in sparse arrays.So if you want maximum performance with sparse arrays, you should benchmark your actual use case.
Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍