This is why I don't use
forEach
anymore.
This benchmark was done against native forEach
, while
, and for
. The code for every function follows this pattern:
function code(arr) {
var res = 0;
// basic count, just to have it do something
arr.forEach(function (i) {
res++;
});
return res;
}
Results
#1: 100,000 items
for.js x 15,954 ops/sec ±0.66% (96 runs sampled)
forEach.js x 238 ops/sec ±0.63% (88 runs sampled)
while.js x 11,145 ops/sec ±0.58% (98 runs sampled)
#2: 100 items
for.js x 8,707,075 ops/sec ±0.70% (96 runs sampled)
forEach.js x 225,990 ops/sec ±0.68% (95 runs sampled)
while.js x 7,120,332 ops/sec ±0.60% (97 runs sampled)
#3: 10 items
for.js x 21,242,096 ops/sec ±0.94% (95 runs sampled)
forEach.js x 1,655,402 ops/sec ±0.68% (95 runs sampled)
while.js x 20,882,718 ops/sec ±0.65% (94 runs sampled)
Obviously, benchmarks don't reflect real-world usage. However, there are precisely zero situations in which a forEach
will be faster than a for
or while
.