Thursday, April 16, 2009

Quick tips for optimizing your jQuery technique

Optimize your Selectors for speed

Selector Speed
  1. #id
  2. tag
  3. .class
  4. Other weird ones

It could be that some of the other selectors can be faster than class. I haven't done extensive research, so if you're in doubt try it out.

While it's okay in your css to have verbose selectors that describe the structure more accutely e.g. #page #header #nav .current, doing this can really slow down jQuery selector speed. Remember that you don't have to worry about the cascade affect in jQuery, just be concise. The Sizzle Selector Engine of jQuery 1.3 also processes selectors in a right to left fashion, so in the example above it's going to get all elements and check each one for a class matching "current" and then compare the parents of what it finds to the rest of the selector removing anything that doesn't match the pattern. This selector can be made much faster like this #nav li.current. By adding the li jQuery switches from getting all elements to using the DOM getElementsByTagName(), which is much faster, then it just looks up and sees the parent with #nav and stops. A lot less filtering will take place.

Minimize Selections

If you're making the same selections repeatedly in your scripts you should just set a variable.

Can be written as
var $aside = $("#aside").hide();

Evaluate re-selecting as opposed to traversal

Sometimes it can be a lot faster to go $("div.subSection") rather than $(this).children("div.subSection")

So if you're in a situation where it looks like a reselect can be faster try it out and compare. The difference between these can vary a lot so I can't generalize here, but test it in your situation. Don't forget that code readability matters so if the difference is trivial make the code easier to understand.

Rely on jQuery less

As cool as jQuery is often you can get some good speed increases if you switch to plain JavaScript. You don't want to do this all the time as jQuery solves a lot of browser bugs that could be a real time sink. But if you're noticing a slow sort function or something that could use a speed up don't be reluctant to fall back to for loop and normal DOM.

Usually, spending a lot time on performance optimization can be a waste, but sometimes it'll really make a difference between a clean responsive UI and one that is so slow that you might as well avoid JavaScript. I know it's easy as an intermediate JavaScripter to rely on libraries for most of what you need to do, but take the time to learn some of the old ways and it can really take your code to the next level.

No comments: