Have you ever experienced forEach being slow and decreasing your application's performance? Do you know why forEach is slow and how we can improve performance? Let's see.

For Each

None

forEach is one of the prebuilt array methods in JavaScript. It invokes a callback function, and this function always returns undefined, unlike other array methods such as map, reduce, and filter.

None

Additionally, forEach only executes the callback function for each assigned index element in the array.

Example code:

const array1 = new Array(4):
array1[0] = "a"
array1[1] = "b"
array1[2] = "c"

array1.forEach((element) => console.log(element));
// output: "a"
// output: "b"
// output: "c"

How Slow forEach

forEach is generally fast and suitable for most operations. It only affects performance when dealing with large datasets or when the callback function takes time to execute, such as when using promises. If your array is small, you don't need to worry about performance."

None

Now, let's see how slow forEach can be. To understand its performance, we will compare it with a traditional for loop.

const arr = Array.from({length:1000000},(_,i)=>i)

console.time("for in")
for(let i = 0;i < arr.length ;i++){
    const r = arr[i] * 4
}
console.timeEnd("for in")
console.time("forEach")
arr.forEach((v)=>{
    const r = v* 4;
})
console.timeEnd("forEach")
for in: 3.555ms
forEach: 9.941ms

Why forEach slow and Why For loop fast

Callback Function Overhead

  • In forEach, the callback function is invoked for each element.
  • First, the execution context is created for one element.
  • Then, when moving to the next element, the previous context is removed and a new one is created.
  • This context switching takes time, which makes forEach slower.
None

However, this problem does not happen in a for loop unless you call a function inside it.

  • If you call a function inside a for loop, the same function overhead occurs.
  • This is known as function call overhead.
const arr = Array.from({length:1000000},(_,i)=>i)

console.time("for in")

for(let i = 0;i < arr.length ;i++){
    function sum(v){
       const r = v * 4
    }
    sum(arr[i])
}

console.timeEnd("for in")
for in: 8.555ms

So, if you think your forEach is slow, just switch to a for loop—performance should improve. Thank you for reading!