Today netmagazine.com published an article highlighting a bunch of javascript performance tips. While focusing on javascript performance is indeed laudable, and I don’t want to be too critical it is also important that we correct malinformation. Sadly this article would happen to lead people slightly off course in their quest to write performant javascript.
I’ve prepared jsperf tests of most the example code from the article so you can judge by yourself:
- Declaring variables
- Building strings
- Division
- Unnecessary method calls within conditionals in For Loops
- Calling methods or properties on array elements
- Local versus Global variables
As you can see for yourself some tips are solid, while others are just not true, but overall theres just one tip I would truly recommend to you and that is that DOM operations are expensive. So dont focus on minor optimiziations, focus on what matters;
- Fewer DOM operations
- Smaller markup
- Simpler CSS
- Minimize your JS
- Browser caching
- JS caching / memoizing.
- Perceived speed (through optimistic operations for example — rendering result before server response).
That being said, some of these tips are good to maintain performance in older browsers. String building through arrays perform far better in old browsers, while its quite well optimized in your normal every day web developers chosen browser. You also need to think about who you are targeting; If you need to cater for a bunch of IE8 users you need a different optimization focus than for Chrome Canary users.