What is better a foreach loop or a normal for?

It is an interesting question and the truth is that I had not considered it. I always try to make the code clear enough, the more the better, rather than worry about performance, which I’m not saying isn’t important, but in almost all applications it’s not that critical.

Of course, two different algorithms can have different performance and you have to take care how you do them to achieve efficiency, but when it comes to using one type of loop or another, little can go wrong. I mean that exactly.

Now, to prove your case and give you an exact answer on what performs better, I’ve benchmarked various loop alternatives, for array traversals.

First I create the structure that we are going to iterate over.

// Build an array of random numbers var myarray = ; for (var i = 0; i < 10; i++) { myarray = Math.random(); }

Now, with that same structure, I have tried the following styles of loops:

Route with a traditional for loop, the one of a lifetime:

for(var i = 0; i < myarray.length; i++) { console.log(myarray); }

Traversal using the forEach method of Javascript arrays:

myarray.forEach(function (item) { console.log(item); });

Traversal using the for…in loop

for (var i in myarray) { console.log(myarray); }

Finally, traversing the array using the for…of loop, which may not be as well known but also helps a lot if you want to take the values ​​and not the indices in each iteration.

for (var i of myarray) { console.log(i); }

Benchmark results

The results I have obtained have surprised me, really. Because the grace is that the performance of these types of loops can depend on the number of elements of the array through which it is going to iterate.

See also  Programs to create PDF

With 1000 elements in the array the forEach loop gets faster. But if there are 10 elements, it is the slowest of the 4. We could say that, if there are few elements, then the traditional for loop wins, but when you have many elements in the array, then the forEach loop is the which offers more performance. But Beware, those benchmark results refer to Chrome, doing the tests in Firefox the results change and the traditional for is always better.

My conclusion is still that it matters little, because these tests do thousands of times the route for there to really be a 10% percentage difference or so in performance. It is not representative. It is more important to focus on the readability of the code.

If you want to experience it for yourselves, I leave you this URL where the benchmark is prepared and you can execute the process and make those changes in the random number array and insert more elements to see how they behave in relation to the number of elements in the array. and in each browser.

https://jsben.ch/rey0z

Loading Facebook Comments ...
Loading Disqus Comments ...