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

Why is passing in a variable (as a ref) slower than accessing the same variable defined in a closure?

本文关键字:变量 定义 闭包 访问 作为 ref 为什么      更新时间:2023-09-26

给定:

(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((时不需要进行变量解析吗?

除了第一次迭代或第二次迭代之外,我没有看到时间上的差异,这表明除了在启动过程中添加了一些东西之外,没有什么大的差异。V8没有立即优化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; }