2

The following seems like a very common practice in Javascript :

for (var i = array.Length - 1; i >= 0; i--) { /* do stuff here */ };

I never noticed this in other languages though ... Does it have any benefits over:

for (var i = 0; i < array.Length; i++) { /* do stuff here */ };

The only thing that comes to mind is the caching of the array length in the first one, which wouldn't be such a huge performance I'd guess. You could also have :

var top =  array.Length;
for (var i = 0; i < top; i++) { /* do stuff here */ };    

Giving you the same benefit of caching, but might be a bit less performant if you are minimizing your code (shaving maybe 8 characters when minifying the script)

Noctis
  • 11,507
  • 3
  • 43
  • 82

2 Answers2

3

Sometimes, it makes a huge difference.

var nodes = element.children, l = nodes.length, i;
for( i=0; i<l; i++) element.removeChild(nodes[i]);
// ^ FAILS WITH ERROR (unless l is 0 or 1)

for( i=l-1; i>=0; i--) element.removeChild(nodes[i]);
// ^ works
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

As mentioned in other answers, going backwards makes things easier when you are removing elements from an array, but it also does provide a slight performance boost as seen in this example (jsperf). I suspect that starting at the end and working your way to the beginning is faster because you don't have to grab the length property of the array after every iteration of the loop.

scribblemaniac
  • 5,951
  • 2
  • 16
  • 14