0

Possible Duplicate:
What is the best way to do loops in JavaScript
What’s the best way to loop through a set of elements in JavaScript?

Any ideas?

6 Answers 6

15

Check this JavaScript loop benchmarks.

Sign up to request clarification or add additional context in comments.

3 Comments

@Plan B: Yeah, look this article also: moddular.org/log/javascript-loops
Hopefully this encourages you to go with whatever is clearest--not fastest. They're all fast.
@Micheal - Yeah in my Opera the first without any optimization is often the fastest...
3

What's wrong with a good old-fashioned for loop?

for( var i = 0; i < list.length; i++ ) {
    // do something with list[i]
}

The semantics of for...in and for...each...in tend to confuse people and lead to unexpected results.

1 Comment

In Javascript variable resolution is late bound. In your example above you would need to resolve length every iteration of the loop. You should cache the length variable by doing for (var i=0, l=list.length;i<l;i++). Good rule of thumb is the less dots the better in JS.
0

CMS's link should show you for small data sets they're all fast, the only thing i'd suggest is that you avoid for (a in b) as it has a much higher memory overhead than any other looping construct and can potentially be much slower due to its "interesting" semantics.

Anyhoo, with the exception of for(in) any real JS should be spending quite a bit more time actually doing real work than is spent handling the looping itself, so minor variation in cost of the loop shouldn't be too important.

Comments

0

As answered elsewhere (why does this thread exist?): the reverse while:

var i = foo.length; while (i--) { /* do something with foo[i] */ }

..is the fastest loop if you can deal with the caveats that:

  • reverse order isn't always suitable

  • it's a bit hard to read

  • it adds a variable to the footprint of whatever scope it's in

  • it's only slightly faster than the smaller footprinted and more readable cached length for loop

2 Comments

If the array is 0 based then you should use --i in the while loop otherwise it will be out of bounds var i = foo.length; while (--i) { /* do something with foo[i] */ }
You can see here that this is not always true: jsperf.com/loops/33. Most loops caching the array's length are more or less equally fast.
0

Supposedly objects are faster... For example:

var array = {"0": "foo", "1": "bar"}
for(var i in array){
    var val = array[i];
    // do something
}

Comments

0

This was covered recently in Greg Reimer's Weblog.

The quick answer is this:

for (var i=0, node; node = hColl[i++];) {
    // do something with node
}

1 Comment

why the i++ there? you will need to use (i-1) to "do something with node"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.