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

查看:33
本文介绍了在 JavaScript 中循环数组的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从书上知道你应该像这样写for循环:

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?

推荐答案

在使用大多数现代浏览器执行此测试后:https://jsben.ch/wY5fo

After performing this test with most modern browsers: https://jsben.ch/wY5fo

目前,最快的循环形式(在我看来也是最明显的句法).

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

带有长度缓存的标准 for 循环

A standard for-loop with length caching

    var i = 0, len = myArray.length;
    while (i < len) {
        // your code
        i++
    }

我想说,这绝对是我为 JavaScript 引擎开发人员鼓掌的案例.运行时应该针对清晰性进行优化,而不是为了聪明.

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

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

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