Performance Tip #1: Variables in the DOM
Advice in a nutshell: Try to declare all your functionality within closures and avoid declaring variables in the global scope or any part on the DOM.
Variable foo can be accessed from anywhere on your page as either foo or window.foo. That sounds great as it’s a way to share data across functions and scripts. While it certainly does that it does it at a cost.
Comparing the two different scripts below, the first reads the variable via the DOM 1 million times the 2nd reads a local variable 1 million times.
Executing the test 10 times and then taking an average I got the following:
Script 1 (DOM)
Script 2 (closure)
As you can see accessing variables via the DOM is a lot slower than accessing them locally, for me it was 8x slower. While a million access might sound like a lot it’s not actually that many, try using the IE8 profiler on some sites as you type an email or chat online and you might be surprised as to how much goes on, a topic for another day.
Bonus Tip: Timings in IE & Date
In IE8 and below the clock used by Date has a resolution of ~10ms but if you go to the developer tools and press start profiling we change the clock resolution to be 1ms. This has some other side affects but nothing to worry about.