Could we help you? Please click the banners. We are young and desperately need the money
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);
}
}
}
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