Comparing performance of javascript forEach and for loop on array of items


Last week i had to optimize javascript code that didn’t perform well enough in Internet explorer (11). Chrome was also not performing very well, so i started searching for performance gains.

There were many Arrays in code and there where many forEach loops. I changed some foreach loops to for loops and performance improved quite a bit.

In this post i will share some code that demonstrates the performance difference of forEach and for loops.

Comparison code

First let’s create an array of 1000001 string values

let items = [];

for (let i = 0; i < 1000001; i++) {
  items.push('sometext-' + i);

Now let’s do a forEach on this array, while keeping track of the time elapsed

let startDate = new Date();
items.forEach(function(item) {
  const doSomething = item;
let elapsed = (new Date()) - startDate;

console.log('forEach finished in ' + elapsed ' ms.');

Then let’s do a for loop on the array values

startDate = new Date();
for (let j = 0, length = items.length; j < length; j++) {
  const doSomething = items[j];
elapsed = (new Date()) - startDate;

console.log('for loop finished in ' + elapsed ' ms.');

If we run this code the console will show something like:

forEach finished in 32 ms

for loop finished in 6 ms

So, as you can see there is a big difference in time it takes to do a forEach in comparison to a for loop.

Plunker example

Go checkout the example code on Plunker


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>