HussienK
HussienK

Reputation: 3022

Why is a for loop faster than Array.prototype.map()

From what I've read here and tested personally using console.time(), a regular for loop in JavaScript is faster than using Array.prototype.map(). Why is that the case?

Upvotes: 3

Views: 281

Answers (1)

user6362627
user6362627

Reputation: 115

I'm assuming your simple for loop looks like this:

var num = [];
for (var i = 0; i < 100; ++i)
  num.push(i);
var result = [];
for (var i = 0; i < 100; ++i)
  result.push(Math.sqrt(num[i]));

That's pretty straight-forward and simplistic. Now let's look at a conforming EMCA-262 implementation:

Taken from spidermonkey

/* ES5 15.4.4.19. */
function ArrayMap(callbackfn/*, thisArg*/) {
    /* Step 1. */
    var O = ToObject(this);

    /* Step 2-3. */
    var len = TO_UINT32(O.length);

    /* Step 4. */
    if (arguments.length === 0)
        ThrowError(JSMSG_MISSING_FUN_ARG, 0, 'Array.prototype.map');
    if (!IsCallable(callbackfn))
        ThrowError(JSMSG_NOT_FUNCTION, DecompileArg(0, callbackfn));

    /* Step 5. */
    var T = arguments.length > 1 ? arguments[1] : void 0;

    /* Step 6. */
    var A = NewDenseArray(len);

    /* Step 7-8. */
    /* Step a (implicit), and d. */
    for (var k = 0; k < len; k++) {
        /* Step b */
        if (k in O) {
            /* Step c.i-iii. */
            var mappedValue = callFunction(callbackfn, T, O[k], k, O);
            // UnsafePutElements doesn't invoke setters, so we can use it here.
            UnsafePutElements(A, k, mappedValue);
        }
    }

    /* Step 9. */
    return A;
}

Can you see why map is slower?

Upvotes: 2

Related Questions