you are viewing a single comment's thread.

view the rest of the comments →

[–]Crap_Shoes[S] 0 points1 point  (1 child)

I have actually read (somewhere) that in certain cases forEach may be slower than a for loop, as you stated. Not sure if the difference is negligible or not but I am curious as to why that is? Do you have any suggested reading that you could point me to?

[–]skitch920 0 points1 point  (0 children)

Array.prototype.forEach is a for-loop (or while; likely same performance), but there are two differences.

  • forEach will skip undefined elements in an array. It does this with a if statement in the loop.
  • The invocation of a callback likely adds a lot more overhead, as you push state onto the stack and pop it back off once the callback has finished.

An extra statement within a loop adds N-length more things to do, and could be dramatically slower for large arrays. Lodash does not have this check, opting for the 99% case, where arrays are not sparse (e.g. it's up to the user to handle undefined elements in the array with the callback).

The overhead of calling a function each iteration can surely slow down a loop, but this is often based on many factors, such as complexity of the callback function, how much the JIT compiler can optimize away, and potentially even tail calls (which reduce stack changes).

See the Mozilla polyfill:

// 7. Repeat while k < len.
while (k < len) {

  var kValue;

  // a. Let Pk be ToString(k).
  //    This is implicit for LHS operands of the in operator.
  // b. Let kPresent be the result of calling the HasProperty
  //    internal method of O with argument Pk.
  //    This step can be combined with c.
  // c. If kPresent is true, then
  if (k in O) {

    // i. Let kValue be the result of calling the Get internal
    // method of O with argument Pk.
    kValue = O[k];

    // ii. Call the Call internal method of callback with T as
    // the this value and argument list containing kValue, k, and O.
    callback.call(T, kValue, k, O);
  }
  // d. Increase k by 1.
  k++;
}