使用额外的var可以改善javascript /在Chrome 50.0.2661.102(64位)Mac下的性能

时间:2016-05-18 21:15:57

标签: javascript performance

免责声明:我发现它可能看起来不成熟,但问题本身就很有趣,所以感谢您的耐心等待。

我有两个用于衡量不同场景表现的jsfiddles,我偶然发现了一个非常有趣的事情:

https://jsfiddle.net/lu4x/k74oq0de/51/

function timeout() {
  var x = 0; // <------------------------------ Using this variable
  for (let iteration = 0; iteration < 1; iteration++) {
    let count = 0;
    let timeA = performance.now();

    for (let i = 0; i < map.length; i++) {
      x = map[i]; // <------------------------------ and this assign
      count += x;
    }

    let timeB = performance.now();
    let delta = timeB - timeA;

    average = avg(average, run, delta);
    minimum = Math.min(minimum, delta);

    if (++run % 100 === 0) log([run, minimum, average]);
  }

  if (iterate) setTimeout(timeout, 0);
}

在我的机器上产生此输出:

1000,19.204999999999927,22.00017499999995
900,19.204999999999927,22.074283333333327
800,19.204999999999927,22.13556875000003
700,19.204999999999927,22.222578571428635
600,19.204999999999927,22.271575000000077
500,19.24000000000069,22.486130000000085
400,19.24000000000069,22.41451250000006
300,19.24000000000069,22.209600000000002
200,19.280000000000655,22.322875000000046
100,19.38000000000011,22.719250000000034

以下小提琴:

https://jsfiddle.net/lu4x/k74oq0de/52/

function timeout() {
    for (let iteration = 0; iteration < 1; iteration++) {
    let count = 0;
    let timeA = performance.now();

    for (let i = 0; i < map.length; i++) {
      count += map[i]; // <--------------------- Not using anything
    }

    let timeB = performance.now();
    let delta = timeB - timeA;

    average = avg(average, run, delta);
    minimum = Math.min(minimum, delta);

    if (++run % 100 === 0) log([run, minimum, average]);
  }

  if (iterate) setTimeout(timeout, 0);
}

产生以下输出:

1000,21.125,24.086139999999997
900,21.125,24.086711111111097
800,21.125,24.068375000000003
700,21.125,24.05558571428569
600,21.165000000000873,24.102566666666636
500,21.165000000000873,24.129959999999983
400,21.165000000000873,24.10507499999996
300,21.170000000000073,24.021016666666657
200,21.170000000000073,24.03779999999997
100,21.300000000000182,24.037549999999992

我做了一些其他测试,差异为21.125 - 19.204999999999927 = 1.92毫秒。对于这种类型的测试,这是一个巨大的变化,惩罚的数量接近于一个解除引用(即x.y)操作。

为什么会发生这种情况。

P.S。

如果将var x放在循环中,它将与不使用var x一样慢。我受宠若惊......

==============

修改

以下是使用benchmark.js

的相同性能测试

https://jsfiddle.net/lu4x/k74oq0de/60/

Benchmark.js确认了先前测试中显示的内容,差异显着

0 个答案:

没有答案