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

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!

Leave a Comment