Any ideas?
See also (dups or near-dups):
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?
What is the best way to do loops in JavaScript
What’s the best way to loop through a set of elements in JavaScript?
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.
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.
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
}
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
Supposedly objects are faster... For example:
var array = {"0": "foo", "1": "bar"}
for(var i in array){
var val = array[i];
// do something
}