Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中遍历数组的最快方法是什么?(What's the fastest way to loop through an array in JavaScript?)

I learned from books that you should write for loop like this:

(我从书中了解到,您应该为循环编写这样的内容:)

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

so the arr.length will not be calculated each time.

(因此不会每次都计算arr.length 。)

Others say that the compiler will do some optimization to this, so you can just write:

(其他人则说编译器会对此做一些优化,因此您可以编写:)

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

I just want to know which is the best way in practice?

(我只想知道哪种是最佳实践?)

  ask by wong2 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After performing this test with most modern browsers...

(在使用大多数现代浏览器执行此测试之后...)

http://jsben.ch/y3SpC

(http://jsben.ch/y3SpC)

Currently , the fastest form of loop (and in my opinion the most syntactically obvious).

(当前 ,最快的循环形式(我认为在语法上最明显)。)

a standard for loop with length caching

(具有长度缓存的循环的标准)

for (var i = 0, len = myArray.length; i < len; i++) {

}

I would say this is definitely a case where I applaud JavaScript engine developers.

(我会说这绝对是我为JavaScript引擎开发人员鼓掌的情况。)

A run time should be optimized for clarity , not cleverness .

(应该优化运行时间以提高清晰度而不是聪明 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...