Created
December 12, 2013 12:06
-
-
Save anselmh/7927046 to your computer and use it in GitHub Desktop.
# Cached and faster `for` loops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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