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?

Community
  • 1
  • 1
Newbie
  • 7,031
  • 9
  • 60
  • 85

6 Answers6

15

Check this JavaScript loop benchmarks.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
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.

Rob
  • 47,999
  • 5
  • 74
  • 91
  • 6
    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 – steve_c Jan 07 '09 at 20:13
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.

olliej
  • 35,755
  • 9
  • 58
  • 55
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
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
nes1983
  • 15,209
  • 4
  • 44
  • 64
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

annakata
  • 74,572
  • 17
  • 113
  • 180
  • 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] */ } – aaronfarr Jun 23 '11 at 00:59
  • You can see here that this is not always true: http://jsperf.com/loops/33. Most loops caching the array's length are more or less equally fast. – Blaise Jan 10 '13 at 10:04
0

Supposedly objects are faster... For example:

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