在 javascript 中迭代数组时,for 循环和 for.. in 循环之间的性能差异? [英] performance difference between for loop and for.. in loop when iterating an array in javascript?

查看:41
本文介绍了在 javascript 中迭代数组时,for 循环和 for.. in 循环之间的性能差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var a = [10,20,30,40];// Assume we have thousands of values here

// Approach 1
var i, len = a.length;
for(i=0;i<len;i++){
  alert(i);
  alert(a[i]);
}

// Approach 2   
for( i in a ){
  alert(i);
  alert(a[i]);
}

推荐答案

使用 for (var i = 0, len = a.length; i < len; i++) 因为它更快更这是正确的方法或迭代数组中的项目.

Use for (var i = 0, len = a.length; i < len; i++) because it's way faster and it's the correct way or iterating the items in an array.

第一:for (i in a) 迭代数组是不正确的,因为除了数组元素之外,迭代还将包括可枚举的属性.如果任何方法或属性已添加到数组中,当使用 for (i in a) 时,它们将成为迭代的一部分,这在尝试遍历数组元素时绝不是您想要的.

First: It's not correct to iterate arrays with for (i in a) because that iteration will include enumerable properties in addition to array elements. If any methods or properties have been added to the array, they will be part of the iteration when using for (i in a) which is never what you want when trying to traverse the elements of the array.

第二:正确的选项要快得多(快 9-20 倍).请参阅此 jsPerf 测试,该测试显示 for (var i = 0; i < len; i++) 选项在 Chrome 中的速度提高了约 9 倍,在 Firefox 中的速度差异甚至更大:http://jsperf.com/for-loop-comparison2.

Second: The correct option is a lot faster (9-20x faster). See this jsPerf test which shows the for (var i = 0; i < len; i++) option to be about 9x faster in Chrome and even more of a speed difference in Firefox: http://jsperf.com/for-loop-comparison2.

作为使用 for (var i in a) 时可能出现的问题的一个例子,当我使用它时,当项目中包含 mootools 库时,我得到了 的所有这些值代码>i:

As an example of the problems that can occur when using for (var i in a), when I use that when the mootools library is included in the project, I get all these values for i:

0
1
2
3
$family
$constructor
each
clone
clean
invoke
associate
link
contains
append
getLast
getRandom
include
combine
erase
empty
flatten
pick
hexToRgb
rgbToHex

这似乎是 mootools 添加到数组对象中的一堆方法.

which appears to be a bunch of methods that mootools has added to the array object.

这篇关于在 javascript 中迭代数组时,for 循环和 for.. in 循环之间的性能差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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