forEach iterates over the entire length of the array, skipping non-existent elements along the way. Although a and b contain only one element, their length large, so you give forEach complicated iteration time.
In the end, it's in the specification! Excerpt ES5 15.4.4.18 Array.prototype.forEach :
6) Let k be 0.
7) Repeat while k <Len
To demonstrate this, let's see how Firefox SpiderMonkey implements the following steps:
for (var k = 0; k < len; k++) { if (k in O) { callFunction(callbackfn, T, O[k], k, O); } }
You can clearly see the cycle k from 0 to len , which underlies your performance problems. For almost all k , k in O gives false , but you still feel the impact of a million iterations and millions of k in O tests.
For reference, here are links to SpiderMonkey and V8 at the time of writing.
source share