As promised, though a day late. The for loop optimization I mentioned at the end of class.
First here is a similar loop like you see everywhere:
CODE
for(var i = 0; i < list.length; i++)
Now this loop seems simple and that nothing can be done to make it faster. But the following are items that slow it down.
i++ explained:
i++ is the shorthand for i = i + 1. This means that the JIT creates an instance scope to find i + 1 then assigns the result to the assignment operator. What slows down the loop is the scope generation. Generally like this:
CODE
var i = 0;
while(i < 100){
i = (function(i) { i = i +1; }); //[url="http://www.lmgtfy.com/?q=javascript+closures"]JavaScript Closures[/url]
}
Now ++i is different in the fact that it doesn't solve for the solution before assigning to i because it does it all in the same scope so it solves and assigns as if you did this loop:
CODE
var i = 0;
while(i < 100){
i = i +1;
}
list.length explained:
It doesn't make sense when you just read and interpret this literally. But what happens really makes plenty of sense. When you request this "property" of the array, the JIT needs to calculate an value instead of reading a property.
Optimized:
for(var i = list.length -1; i >= 0; --i)
Explained:
Assigning the list value allows for a faster process because your computer can count backwards faster then it can forwards when it processes JavaScript.
Pre-decrementing I instead of post-decrementing is also faster since it is the faster of the two decrementing operators.
So overall, taking advantage of the computational powers of the microprocessor and providing the more efficient level of decrementation we have a loop that works for us in our animations instead of code that drags its feet when running.
~~ Bryan Wood
Please note that I composed this while drugged up on thera-flu so if i mistook something let me know.