Why Array.forEach is slower than for() loop in Javascript? [duplicate]

can anyone tell me whats the reason that array.forEach is slower than for loop in javascript. Is there any particular reason.

Here's the code that I was trying to find the performance.

// 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){

Using for loop :

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

I tested it on test runner . Here are the results: enter image description here

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



Updated based on feedback from @BenAston & @trincot

Roughly, this is what's happening in both cases:

For loop

  1. Set the index variable to its initial value
  2. Check whether or not to exit the loop
  3. Run the body of your loop
  4. Increment the index variable
  5. Back to step 2

The only overhead that happens on every iteration is the check & the increment, which are very low-load operations.

forEach loop

  1. Instantiate the callback function
  2. Check if there's a next element to process
  3. Call the callback for the next element to process, with a new execution context (this comprises the "scope" of the function; so its context, arguments, inner variables, and references to any outer variables -- if used)
  4. Run the contents of your callback
  5. Teardown of callback function call
  6. Return to step 2

The overhead of the function setup & teardown in steps 3 & 5 here are much greater than that of incrementing & checking an integer for the vanilla for-loop.

That said, many modern browsers recognize & optimize forEach calls, and in some cases, the forEach might even be faster!


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.