Skip to content

Instantly share code, notes, and snippets.

@getify
Created September 29, 2010 16:20
Show Gist options
  • Select an option

  • Save getify/603041 to your computer and use it in GitHub Desktop.

Select an option

Save getify/603041 to your computer and use it in GitHub Desktop.
for (var i = 0, j = foo.length; i < j; i++) {
// do stuff
}
for (var i = foo.length; i;) {
// first usage in loop: blah[--i]
// do stuff slightly faster in reverse order
}
@getify
Copy link
Copy Markdown
Author

getify commented Sep 29, 2010

@bentruyman
Copy link
Copy Markdown

I'm not sure about this. Seems like that second loop is the slowest of all (at least in Chrome).
http://jsperf.com/for-loop-test/2

@getify
Copy link
Copy Markdown
Author

getify commented Sep 29, 2010

Fixed your test cases:

http://jsperf.com/for-loop-test/3

@bentruyman
Copy link
Copy Markdown

Not sure how that fixed it. It still seems like it's the slowest. Also, I'd opt for the cleaner syntax instead of decrementing inside of the loop.

@getify
Copy link
Copy Markdown
Author

getify commented Sep 29, 2010

it wasn't slowest for me, it was 1% faster in the chrome6 test i initially ran. it definitely wasn't the 20% slower that your revision had.

@getify
Copy link
Copy Markdown
Author

getify commented Sep 29, 2010

also, i didn't claim it was better/cleaner syntactically. it is shorter, and at least as fast if not faster. but any such for-loop optimizations have to be taken with the grain of salt that the code will only be written and maintained by people who understand such syntax.

@getify
Copy link
Copy Markdown
Author

getify commented Sep 29, 2010

just updated again to fix minor issues.

http://jsperf.com/for-loop-test/4

Again, the last test is performing almost the same as the others, and sometimes 1% faster. definitely not statistically slower.

@bentruyman
Copy link
Copy Markdown

That might be the case in the particular version of Chrome 6 you were using to test. In the tests I performed, however, there was a greater than 1% difference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment