Loop optimization
Here’s a little nuance about loops that I never thought of before. If you are looping through an array you would probably write the code like this:
output:0 of 4 : Star Wars
1 of 5 : LOTR
2 of 5 : Matrix
3 of 5 : Superman
4 of 5 : Close Encounters
You’ll notice that I’m adding an element to the array which I’m looping through. That’s almost never a good idea. However I want to illustrate something with this. I add to the array after tracing the output so the first time through the loop the length is 4. Each time afterwards it was 5. And the for/loop noticed this.
Here’s the important thing: each time through the loop the for-conditions are rechecked. That means movies.length is evaluated over and over again. To optimize the loop we could create a variable that holds the value of the array length and then use that in the for-condition. That way the array length is only evaluated once.
The change would look like this:
output:
0 of 4 : Star Wars
1 of 5 : LOTR
2 of 5 : Matrix
3 of 5 : Superman
You can see that the movies.length was still increased but the loop didn’t run through it because the variable is set before loop runs.
If the array that you are looping through is going to change during the loop then you must use the first approach. But it’s unlikely that you’ll do that often, or hopefully ever, so go with the second case and you’re code will run faster.
While you’re at it you can optimize even further by looping through the array backwards. The Flash VM can count backwards through a loop faster than it can forwards.
If something here has proved valuable to you then feel free to drop a couple of bucks in the tip-jar.






