The question: Is one jQuery selector faster and more efficient than another?
The short answer: Absolutely!
The not so short answer: Aaabbsssooolutelyyyyy!!!!
The answer you want: Wrote over 11,000 lines of jQuery code split across 13 files (13 is my lucky number). So after a few months decided to run some tests on the code to see how well it performed. One of the first things that became very obvious is that the jQuery selector can and will make a big difference to how your web-page's scripts perform.
In case you were thinking that we are talking about saving 100ms, it's not! Some of the pages went from loading for over 3 seconds to sub-second. In today's world the users' expectations are much higher than 5 years ago. And its not just the performance of your page load, but as web technology moves full-speed into the Ajax world, the users expect not just fast page refreshes but instant Ajax response times.
Is it worth spending some time learning the ins-and-outs of selector performance? You bet!
Here are some pointers that will help your performance quite a bit:
- Whenever possible use the id selector: $(‘#myId’)
- Never select a class alone unless you have no choice. Just selecting the class is probably one of the worst performing selectors in the jQuery arsenal. There are very good reasons for this but this is not the place to discuss it. So when you know what the container tag is, provide it, which means in stead of $(‘.myClass’) specify $(‘div.myClass’).
- Don’t get too fancy. Long selectors don’t perform very well. In this case shorter is better. For example in some places I thought it may be more efficient to specify $(‘#outerContainer #innerContainer, #wrapper #me’) to get to “me” where just specifying $(‘#me’) performs much faster. In this example especially using nested ids always performs more poorly and is “bad design” for a lack of a better word on the part of the selector, not the HTML, since the id is supposed to be unique within the page anyway.
- Whenever a selector is being used repeatedly, assign it to a var and use the variable. This improves performance quite a bit. For example in stead of:
var $myOuter = $(‘div.outer’);
There is more but these will make a big impact on your jQuery performance. Just because you can do it in jQuery does not mean you should.