我从书中学到,你应该这样写for循环:

for(var i=0, len=arr.length; i < len; i++){
    // blah blah
}

所以arr。每次不计算长度。

其他人说编译器会做一些优化,所以你可以这样写:

for(var i=0; i < arr.length; i++){
    // blah blah
}

我只是想知道在实践中哪种方法是最好的?


当前回答

我总是用第一种体裁写作。

即使编译器足够智能,可以为数组优化它,但如果我们在这里使用DOMNodeList或一些计算长度的复杂对象,它仍然是智能的?

我知道关于数组的问题是什么,但我认为用一种风格编写所有循环是一个很好的实践。

其他回答

虽然这是一个非常古老的问题,但也是一个非常有趣的问题,

请原谅我稍微改变一下这个问题,但我会在最后回答这个问题。

这个问题让我问自己,在js中是否有更好的循环方法:

所以我做了一些测试,以下是我的发现:

对于1000_000记录:最好是forEach。

对于100条记录:这根本不重要。


回到你刚才的问题:

我创建的例子和问题不完全一样。但我发现了一些有趣的事情:

首先,就像你说的,arr。如果它在比较语句I < arr内,Length每次都会计算。长度……

注意:下面的arrLength变量不超过1000_000条记录的数量。

例如:这不会工作

但是这个会

这需要0.036秒。与数字不变的情况相比,这是非常大的……


总之,

最好使用FOREACH

在你的例子中,i<arr。长度需要更多的时间(通常在1.3左右)

请参阅测试: 查看测试

我总是用第一种体裁写作。

即使编译器足够智能,可以为数组优化它,但如果我们在这里使用DOMNodeList或一些计算长度的复杂对象,它仍然是智能的?

我知道关于数组的问题是什么,但我认为用一种风格编写所有循环是一个很好的实践。

截至2016年6月,在最新的Chrome上做了一些测试(2016年5月,浏览器市场份额为71%,并且还在增加):

The fastest loop is a for loop, both with and without caching length delivering really similar performance. (The for loop with cached length sometimes delivered better results than the one without caching, but the difference is almost negligible, which means the engine might be already optimized to favor the standard and probably most straightforward for loop without caching). The while loop with decrements was approximately 1.5 times slower than the for loop. A loop using a callback function (like the standard forEach), was approximately 10 times slower than the for loop.

我相信这个线程太旧了,它误导程序员认为他们需要缓存长度,或者使用反向遍历,同时递减来获得更好的性能,编写的代码不太容易读懂,更容易出错,而不是简单直接的for循环。因此,我建议:

If your app iterates over a lot of items or your loop code is inside a function that is used often, a straightforward for loop is the answer: for (var i = 0; i < arr.length; i++) { // Do stuff with arr[i] or i } If your app doesn't really iterate through lots of items or you just need to do small iterations here and there, using the standard forEach callback or any similar function from your JS library of choice might be more understandable and less prone to errors, since index variable scope is closed and you don't need to use brackets, accessing the array value directly: arr.forEach(function(value, index) { // Do stuff with value or index }); If you really need to scratch a few milliseconds while iterating over billions of rows and the length of your array doesn't change through the process, you might consider caching the length in your for loop. Although I think this is really not necessary nowadays: for (var i = 0, len = arr.length; i < len; i++) { // Do stuff with arr[i] }

http://jsperf.com/caching-array-length/60

我准备的最新版本的test(通过重用旧版本)显示了一件事。

缓存长度并不是那么重要,但也没有坏处。

在Chrome、Opera和Firefox中,在我的Debian Squeeze 64位(我的桌面硬件)中,每次第一次运行上面链接的测试(在新打开的选项卡上),最后4个片段(图表中的第3、第5、第7和第10)的结果都是最好的。随后的运行给出了完全不同的结果。

性能方面的结论很简单:

使用for循环(向前)并使用!==而不是<进行测试。 如果以后不需要重用数组,那么while循环减去长度和破坏性shift()-ing数组也是有效的。


博士tl;

现在(2011.10)下面的模式看起来是最快的。

for (var i = 0, len = arr.length; i !== len; i++) {
    ...
}

注意缓存。长度在这里并不重要,所以您可以只测试I !== arr。长度和性能不会下降,但是代码会变短。


PS:我知道在snippet with shift()中,它的结果可以用来代替访问第0个元素,但我在重用以前的修订(有错误的while循环)后忽视了这一点,后来我不想失去已经获得的结果。

现在是2022年底

有时根本没有用数组长度计算:

如果你有一个索引为var myArray =[1,2,3,4,25,99999999999999]的数组,使用任何索引为1的槽数组(包括forEach)的解决方案都是非常缓慢的。

对我来说,最好的解决方案是:

for(let _i in myArray ) {
   if(myArray[_i]) {
     (function(s) {
        ///
     })(myArray[_i]) 
   }
}