【发布时间】:2011-10-21 21:11:52
【问题描述】:
我读到not reading the length attribute of an array every iteration in the loop header 建议优化 JavaScript 中的循环。
所以,我们应该这样做:
var names = ['George','Ringo','Paul','John'];
for(var i=0,j=names.length;i<j;i++){// Read array length once and assign it to a variable
doSomeThingWith(names[i]);
}
而不是这个:
var names = ['George','Ringo','Paul','John'];
for(var i=0;i<names.length;i++){
doSomeThingWith(names[i]);
}
但是,我created a small testcase 比较了这两种技术,但有时第一种情况更快,有时第二种情况。
您会推荐哪个版本?
【问题讨论】:
标签: javascript performance optimization loops for-loop