开发者

JavaScript: Looping over array

开发者 https://www.devze.com 2023-01-20 01:16 出处:网络
Would开发者_开发知识库 it be wrong to conclude that the fastest way to loop over a JavaScript array would be to use the for-in loop? E.g.:

Would开发者_开发知识库 it be wrong to conclude that the fastest way to loop over a JavaScript array would be to use the for-in loop? E.g.:

for (var index in items) {
    ...
}

See http://jsperf.com/loop-test2/2


The for-in statement shouldn't be used to iterate over array or array-like elements.

The purpose of this statement to enumerate object properties.

It shouldn't be used for array-like objects because:

  • The order of iteration is not guaranteed, the array indexes may not visited in the numeric order.
  • Inherited properties are also enumerated.

To iterate over an array, a sequential loop is always recommended.

Recommended article:

  • Enumeration VS Iteration

Edit: Oh also, I forgot to mention that your test is completely biased, because the expression new Array(10000) simply initializes an Array object with 10000 as the value of the length property, the numeric index properties don't even exist, that's why it seems to be the fastest e.g.:

var a = new Array(10);
a.length; // 10
a.hasOwnProperty('0'); // false, the indexes don't even exist!
a.hasOwnProperty('1'); // false
//...

Try this fair test, with an array object that really contains 10000 elements and you will be surprised. :)


Yes it can be the fastest, but it isn't safe and not a for-in loop's purpose...so it's really a moot point.

Something being fast isn't a concern until it's correct :)

For example test this in IE: http://jsfiddle.net/nick_craver/z52gx/ You'll notice the order is incorrect.


Whether or not it's the fastest is implementation dependent. Consider that each major browser vendor has their own implementation, plus a mobile implementation, plus all the old browsers still in use and beta browsers demoing next-gen javascript engines... there's "only" about 30 different javascript implementations out there right now. And even if this is currently fastest on all or most of those, javascript engines are still rapidly evolving.

And that's even assuming that javascript is your bottleneck. Here's a tip - as slow as javascript is, it's rarely the bottleneck for page rendering. Internet tranfer speeds and server response times tend to be much more important factors.

Maybe it's a better idea to code for correctness first.


This is a little out of date (Only includes FF3.0 and IE8b), but it's pretty comprehensive.

http://blogs.oracle.com/greimer/entry/best_way_to_code_a

Reverse while loops with a simplified condition look the fastest:
var len; while(len--){}

0

精彩评论

暂无评论...
验证码 换一张
取 消