Why is Array.forEach running slower than the for () loop in Javascript?

Can someone tell me that the reason array.forEach is slower than for a loop in javascript. Is there any special reason.

Here is the code I was trying to find.

// Populate the base array
    var arr = [];
    for (var i = 0; i < 1000; i++) {
      arr[i] = i;
    }

    function someFn(i) {
      return i * 3 * 8;
    }

Using Array.forEach:

arr.forEach(function (item){
  someFn(item);
})

Usage for the loop:

for (var i = 0, len = arr.length; i < len; i++) {
  someFn(arr[i]);
}

I tested it on a tester. Here are the results: enter image description here

As you can see, Array.ForEach is 96% slower than for a loop. Thanks in advance.

+4
source share
1 answer

Updated based on reviews from @BenAston and @trincot

Roughly speaking, this is what happens in both cases:

For the cycle

  • Set the index variable to its initial value
  • ,
  • 2

, , , .

Each

  • ,
  • ( "" , , , - )
  • 2

3 5 , .

, , , forEach !

+4

Source: https://habr.com/ru/post/1676548/


All Articles