Anytime you can eliminate a procedure inside of a loop, do it. See tip 2: Shorten object chains.
The amount of performance benefit gained will be equivalent to (procudure_duration × number_of_iterations) - 1.
If a procedure in a loop takes 30ms and the loop iterates 20 times, that translates to 570ms in wasted processing.
| Ease | Effectiveness | Overall Practicality | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| 9 |
|
10 |
for(var i = 0; i < collection.length; i++){ }
Can be more efficiently written as:
for(var i = 0, len = collection.length; i < len; i++){ }
| Ease | Effectiveness | Overall Practicality | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| 9 |
|
8 |
Precalculating the length of a loop will have a minimal effect per iteration, in most cases. If the length variable is reused in the body of the loop, the benefit will be greater. It is very easy to do and doesn't obfuscate the code, so we just do it anyway.
Iterative solutions are usually (not always) more efficient. Sometimes a recursive solution is the only natural solution. When an iterative solution to a recursive problem gets confusing, it is okay to stick to recursion.
| Ease | Effectiveness | Overall Practicality | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| 2 |
|
3 | ||||||||
Next in this tutorial: Strings