OK, so that being said here are the two main optimization tweaks I’ve learned so far.
Local Is Faster Than Anything Else
If I could boil all of chapter two into one rule. This would be it. Any time you are accessing a variable, make sure you turn it into a local variable if you are going to use that data more than once in your local scope.
Why is this?
And be careful thinking that just because it is a property, you can ignore this rule. Even properties take more time than going after a local variable. At a minimum it has to do a lookup for the variable that represents the object and another lookup for the property or method attached to that object.
In a compiled language, this generally isn’t necessary because these references are all figured out when we compile the code. So you’ll need to get your head out of “compiled language mode” and back into scripting mode.
Avoid Accessing the DOM
But the point of this rule is that we want to avoid accessing the DOM any more than we absolutely have to.
Why is this slow?
Second, manipulating the DOM is slow. Historically this was not such a huge problem because the DOM was only expected to be rendered once.
So what can you do to help your performance?
Second, don’t do anything in multiple calls that you could do with one.
What Else Is In The Book?
- Loading and Execution – How to optimize getting the code on the client side to start with.
- Data Access – All about variables
- DOM Scripting – Optimizing access to the DOM
- Algorithms and Flow Control
- Strings and Regular Expressions
- Responsive Interfaces
- Programming Practices
- Tools – Profilers, etc.
I’ve learned a lot in a few days and it has changed how I look at my code. The book is really easy to read and even though it has a 2010 copyright on it, and lacks metrics for current browsers, 99% of the material still applies.