Skip to content

Instantly share code, notes, and snippets.

@anselmh
Created December 12, 2013 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anselmh/7927046 to your computer and use it in GitHub Desktop.
Save anselmh/7927046 to your computer and use it in GitHub Desktop.
# Cached and faster `for` loops
/*
* The trouble with collections is that they are live queries against the underlying document (the HTML page). This means that every time you access any collection’s length, you’re querying the live DOM, and DOM operations are expensive in general.
*
* It's only good if you don't update the length by f.e. adding DOM nodes
*
* That’s why a better pattern for for loops is to cache the length of the array (or collection) you’re iterating over, as shown in the following example:
*/
for (var i=0, max = myarray.length; i < max; i++) {
// do sth.
}
// more options:
for (var i=0, max=myarray.length; i < max; i=i+ 1) {
// do sth.
}
// micro-optimization:
var i, myarray = [];
for (i = myarray.length; i < max; i=i+ 1) {
// do sth.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment