在JavaScript中,为什么“反向”循环比“for”快一个数量级? [英] In JavaScript, why is a "reverse while" loop an order of magnitude faster than "for"?

查看:159
本文介绍了在JavaScript中,为什么“反向”循环比“for”快一个数量级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这些基准测试中,Barbara Cassani表示:一个反向while循环的速度更快,

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

比通常的for循环:
(i = 0; i a = a + 1;

  
a = a - 1;



$ b $为什么?

更新



好吧,忘了它,在测试中有一个错误, iterations = 100 ,每页仅执行一次。因此,减少它意味着我们并不真正进入循环。对不起。

解决方案

除了最初的测试中的大错误,以下是结果:


  • vs 没有区别

  • ,但> < 优于!= =



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


In these benchmarks, http://jsperf.com/the-loops, Barbara Cassani showed that a "reverse while" loop is way faster,

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

than a usual "for" loop:

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

Why?

Update

Okay, forget about it, there is a bug in the test, iterations = 100, is executed only once per page. Therefore reducing it, well, means that we don't really enter the loops. Sorry.

解决方案

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

这篇关于在JavaScript中,为什么“反向”循环比“for”快一个数量级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆