4

在这些基准测试中,http ://jsperf.com/the-loops,Barbara Cassani 表明“反向 while”循环要快得多,

while (iterations > 0) {
    a = a + 1;
    a = a - 1;
    iterations--;
}

比通常的“for”循环:

for (i = 0; i < iterations; i++) {
    a = a + 1;
    a = a - 1;
}

为什么?

更新

好吧,算了,测试有个bug,iterations = 100每页只执行一次。因此,减少它意味着我们并没有真正进入循环。对不起。

4

2 回答 2

2

Except for the big bug in the initial test, here are the results:

  • for vs while makes no difference
  • but > or < are better than !==

http://jsperf.com/the-loops/15

于 2012-06-01T11:29:38.647 回答
1

这是因为每个 JavaScript 引擎的内部细节。不要将它用于优化,因为你不能在逻辑上指望它总是随着引擎的变化而变得更快。例如,查看您链接的测试的最新版本,并注意如果在最近的浏览器上存在差异,则差异要小得多。

于 2012-06-01T10:30:58.177 回答