Menü schliessen
Created: November 25th 2021
Last updated: April 21st 2022
Categories: Common Web Development,  IT Development,  JavaScript Development
Author: Tim Fürer

JavaScript: forEach Performance & Optimization

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

JavaScript's native "forEach" is slow. If you were to recreate "forEach" using the native "for" loop, from that alone, you'd have about 30% performance gain. That's insane, isn't it?

Insane, but not illogical. If you didn't know yet, "forEach", at least for JavaScript, is a new concept and hasn't been properly optimized so far.

"forEach" is very useful, but so is it painful due to the lost speed. While you can, as I've mentioned earlier, recreate "forEach" with "for", it's quite the hassle and results in bad readability.

Until "forEach" is optimized on a native basis, I've got a solution for you: A wrapper function for a "for"-based "forEach"; Have a syntax as nice as "forEach's" at the performance of "for".

function foreach(arr, f) {
    if (arr.length) {
        for(let i = 0; arr.length > i; i++) {
            f(arr[i], i, arr);
        }
    }
}

How Do I Use This Custom forEach?

It's relatively simple and similar to the native "forEach". The function's first parameter is the array to loop through and the second, the function to run with each iteration of the loop. That iteration function has three optional parameters: "value", "index", and "array". As their names suggest, they return the current loop value, index, and the array itself.

Syntax:

foreach(array, function(value, index, array) {
    // Do Stuff
});

Example:

const fruits = ['apple', 'orange', 'banana'];

foreach(fruits, function(v, i) {
    console.log(`Index ${i}: ${v}`);
});

// logs the following into console:
// Index 0: apple
// Index 1: orange
// Index 2: banana

Helpful Resources