[英]Why is there a performance difference between these two reverse loops?
Note: To run just the following two tests on that benchmark suite, click on Basic reverse for loop
and Falsy reverse for loop
. 注意:要在该基准套件上仅运行以下两个测试,请单击
Basic reverse for loop
和Falsy reverse for loop
。
The ops/sec listed below are on Chrome 32, Win 7 64-bit. 下面列出的操作/秒是在Chrome 32(Win 7 64位)上进行的。
This loop 这个循环
for (var i=a.length - 1; i >= 0; i--) { } // 1,161,089 ops/sec
is much faster than 比快得多
for (var i=a.length; i--;) { } // 870,837 ops/sec
on Chrome 32, Firefox 27, and Opera 12 & 19. They're about equal in IE (5 - 11) and the falsy loop is actually faster in Safari Windows (5.1.7). 在Chrome 32,Firefox 27和Opera 12和19上使用。它们在IE(5-11)中几乎相等,而在Safari Windows(5.1.7)中,错误循环实际上更快。 This doesn't seem to have anything to do with the loop conditional being falsy - there's another benchmark in that suite for that comparison.
这似乎与循环条件为假无关,这与该套件中还有另一个基准进行比较。
The "basic" loop is about 33% faster than the "falsy" loop on Chrome 32, Win 7 64-bit. 在Chrome 32(Win 7 64位)上,“基本”循环比“虚假”循环快33%。 Why?
为什么?
That second loop: for (var i=a.length; i--;) { }
iterates until i--
returns false, since that part is written in the condition part of the loop. 第二个循环:
for (var i=a.length; i--;) { }
迭代直到i--
返回false,因为该部分写在循环的条件部分中。 i--
will return false when i equals 0, so the functionality of the two loops is the same. 当i等于0时,
i--
将返回false,因此两个循环的功能相同。
However, the second loop causes the additional task of casting each of the values between a.length and 0 to a Boolean, which is more time consuming than integer comparison. 但是,第二个循环导致将a.length和0之间的每个值都强制转换为布尔值的附加任务,这比整数比较耗时更多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.