循环是否真的更快? [英] Are loops really faster in reverse?

查看:174
本文介绍了循环是否真的更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经听过好几遍了。向后计数JavaScript循环真的快吗?如果是这样,为什么?我见过一些测试套件的例子,显示反向循环更快,但我找不到任何解释为什么!



我假设这是因为循环不再需要评估一个属性,每次检查它是否完成,它只是检查最终的数值。

Ie

  for(var i = count  -  1; i> = 0; i--)
{
// count只计算一次,然后比较总是在0.
}


我 - 比 i ++ 更快。实际上,它们都是同样快的。



每个 i 数组的大小。在这个循环中:

  for(var i = array.length; i--;)

当您声明时,只评估一次 .length ($ i $ / code>),而对于这个循环

  for(var i = 1; i <= array。 length; i ++)

您评估 .length 每次你增加 i ,当你检查 i <= array.length



在大多数情况下,您甚至不必担心这种优化

I've heard this quite a few times. Are JavaScript loops really faster when counting backward? If so, why? I've seen a few test suite examples showing that reversed loops are quicker, but I can't find any explanation as to why!

I'm assuming it's because the loop no longer has to evaluate a property each time it checks to see if it's finished and it just checks against the final numeric value.

I.e.

for (var i = count - 1; i >= 0; i--)
{
  // count is only evaluated once and then the comparison is always on 0.
}

解决方案

It's not that i-- is faster than i++. Actually, they're both equally fast.

What takes time in ascending loops is evaluating, for each i, the size of your array. In this loop:

for(var i = array.length; i--;)

You evaluate .length only once, when you declare i, whereas for this loop

for(var i = 1; i <= array.length; i++)

you evaluate .length each time you increment i, when you check if i <= array.length.

In most cases you shouldn't even worry about this kind of optimization.

这篇关于循环是否真的更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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