admin管理员组文章数量:1390547
When I want to loop
through an array
and add a string behind every 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
?
When I want to loop
through an array
and add a string behind every 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
?
- 5 For performance check, try jsperf. – MaxArt Commented Jun 8, 2012 at 12:07
-
1
Note that in both cases you are adding a string to the index of each element, which will break the second loop (it's broken anyway since you never initialize
x
). – Felix Kling Commented Jun 8, 2012 at 12:09 - did you execute and check the output. It's not clear what you want to do. – Romil Kumar Jain Commented Jun 8, 2012 at 12:11
-
3
Never use
for … in
to loop through an array, see developer.mozilla/en/JavaScript/Reference/Statements/… and stackoverflow./questions/500504/… – Marcel Korpel Commented Jun 8, 2012 at 12:17 - 1 jsperf./forinvsfor/5 about 12 times faster in chrome – Esailija Commented Jun 8, 2012 at 12:18
2 Answers
Reset to default 5It is remended that you don't use for ... in
to iterate over arrays.
i.e. Why is using "for...in" with array iteration a bad idea?
You should use for ... in
to iterate over object properties only.
Usually, for...in
is way slower, because it accesses to the array as a mon object, while the classic for
cycle doesn't need to sort out all the properties of array
to perform its task.
Keep in mind that modern browsers have special optimizations for arrays, but you can't exploit them if you're treating them as mon objects.
本文标签:
版权声明:本文标题:javascript - Performance's difference between for (var x in array) and for (var x=0, y= array.length; x<y; x++) - 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744750608a2623152.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论