在JavaScript中循环数组的最快方法是什么? [英] What's the fastest way to loop through an array in JavaScript?

查看:144
本文介绍了在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
}

所以每次都不会计算 arr.length

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

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

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?

推荐答案

用大多数现代浏览器执行此测试后......

After performing this test with most modern browsers...

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++) {

}

我想这肯定是我鼓掌JavaScript引擎的情况开发人员。运行时间应针对清晰度进行优化,不要聪明

I would say this is definitely a case where I applaud JavaScript engine developers. A run time should be optimized for clarity, not cleverness.

这篇关于在JavaScript中循环数组的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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