为什么传入变量(作为ref)比访问闭包中定义的相同变量要慢?

时间:2016-08-13 06:50:46

标签: javascript

假设:

(function() {
    var items = [1, 2, 3, 4];

    // In Chrome, this takes ~8-10 ms to execute.
    for(var i = 0; i < items.length; i++) {
        x(items);
    }

    // In Chrome, this takes 1-2 ms to execute.
    for(var i = 0; i < items.length; i++) {
        y();
    }

   function x(y) {
        y[0] = -100;
    }

    function y() {
        items[0] = 100;
    }
})();

为什么对x()的调用比对y()的调用慢8-10倍?是因为在执行y()时不需要进行变量分辨率吗?

1 个答案:

答案 0 :(得分:0)

我没有看到时间上的差异,除了第一次迭代或2,这表明除了在启动期间添加的东西之外没有太大的区别。 V8 doesn't optimize immediately AFAIK这样可以解释为什么需要几次迭代来平衡。还缓存未命中。

function log() {
  var div = document.createElement("div");
  div.textContent = Array.prototype.join.call(arguments, " ");
  document.body.appendChild(div);
};

(function() {
    var items = new Array(10000000);

    for (j = 0; j < 20; ++j) {
      var xStart = performance.now();
      for(var i = 0; i < items.length; i++) {
          x(items);
      }
      var xDuration = performance.now() - xStart;

      var yStart = performance.now();
      for(var i = 0; i < items.length; i++) {
          y();
      }
      var yDuration = performance.now() - yStart;
      log(j, "x:", xDuration.toFixed(3) + "ms",
          "y:", yDuration.toFixed(3) + "ms",
          "diff:", (xDuration - yDuration).toFixed(3) + "ms");
    }
  
    function x(y) {
        y[0] = -100;
    }

    function y() {
        items[0] = 100;
    }
})();
body { font-family: monospace; }