哪个会更快?

时间:2018-06-02 22:56:12

标签: javascript optimization

其中哪一项会更快,或者它们基本上会花费相同的时间。

for(var i = 0; i < 10; i++)
{
    c.fillStyle = "black";
    c.fillRect(5 + i * 2, 5, 5, 5);
    c.fillStyle = "red";
    c.fillRect(5 + i * 2, 15, 5, 5);
}

VS

c.fillStyle = "black";
for(var i = 0; i < 10; i++)
{
    c.fillRect(5 + i * 2, 5, 5, 5);
}

c.fillStyle = "red";
for(var i = 0; i < 10; i++)
{
    c.fillRect(5 + i * 2, 15, 5, 5);
}

1 个答案:

答案 0 :(得分:1)

如果迭代次数不是很大,那么他们所需的时间几乎完全相同,但是如果你有一个吨,那么最好避免重新分配c.fillStyle,这看起来很慢大约减少5倍:

&#13;
&#13;
const c = document.querySelector('canvas').getContext('2d');

function oneLoop() {
  for (var i = 0; i < 500000; i++) {
    c.fillStyle = "black";
    c.fillRect(5 + i * 2, 5, 5, 5);
    c.fillStyle = "red";
    c.fillRect(5 + i * 2, 15, 5, 5);
  }
}

function twoLoops() {
  c.fillStyle = "black";
  for (var i = 0; i < 500000; i++) {
    c.fillRect(5 + i * 2, 5, 5, 5);
  }

  c.fillStyle = "red";
  for (var i = 0; i < 10; i++) {
    c.fillRect(5 + i * 2, 15, 5, 5);
  }
}
[oneLoop, twoLoops].forEach(fn => {
  const start = performance.now();
  fn();
  const end = performance.now();
  console.log(end - start);
});
&#13;
<canvas></canvas>
&#13;
&#13;
&#13;