为什么for循环比Array.prototype.map()

时间:2016-05-20 18:40:05

标签: javascript

通过我在此处阅读并使用console.time()进行个人测试,JavaScript中的常规for循环比使用Array.prototype.map()更快。为什么会这样?

1 个答案:

答案 0 :(得分:1)

我假设您的简单for循环看起来像这样:

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]));

这非常简单直接。现在让我们看一下符合要求的EMCA-262 implementation

取自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;
}

你能看出为什么map会变慢吗?