简体   繁体   English

for(var x in array)和for(var x = 0,y = array.length; x之间的性能差异

[英]Performance's difference between for (var x in array) and for (var x=0, y= array.length; x<y; x++)

When I want to loop through an array and add a string behind every element , 当我想loop通过array ,并添加每个后面的字符串element

I can either 我可以

for(var x in array){
 array[x] += "string";  
}

or 要么

for(var x, y = array.length; x<y; x++){
 array[x] += "string";  
}

But is there any difference in terms of performance between these 2 for loops ? 但是,这两个for loops之间在性能方面什么区别吗?

It is recommended that you don't use for ... in to iterate over arrays. 建议您不要使用for ... in来遍历数组。

ie Why is using "for...in" with array iteration a bad idea? 为什么在数组迭代中使用“ for ... in”是个坏主意?

You should use for ... in to iterate over object properties only. 您应该使用for ... in来仅遍历对象属性。

Usually, for...in is way slower, because it accesses to the array as a common object, while the classic for cycle doesn't need to sort out all the properties of array to perform its task. 通常, for...in的速度要慢一些,因为它作为一个公共对象访问数组,而经典的for cycle不需要整理array所有属性即可执行其任务。

Keep in mind that modern browsers have special optimizations for arrays, but you can't exploit them if you're treating them as common objects. 请记住,现代浏览器对数组进行了特殊的优化,但是如果将它们视为通用对象,则无法利用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM