CSS Practices for jQuery Performance
In this article, we're going to do some comparisons of jQuery performance to show how different ways of coding HTML and CSS can make a big difference. These tests are not meant as a browser comparison but to show that the results are consistent across them.
The first test is a comparison between a class and an id for getting a single page element.
Class Versus Id
The result of this first test is no surprise. A clear winner in all browsers is using an id selector. An id is guaranteed to be unique to the page and there is a JavaScript API call to get the dom element with an id. If you're going to need to look for something unique on the page and it's easy to give it an id then do so.
On the other hand, using ids in CSS is a bad idea. It makes it too hard to share style rules and have more than one of something on the page. So, classes are the way to go in CSS.
[table=tables-grid summary="Class Versus Id jQuery Performance" Browser | jQuery(".class") | jQuery("#id") FireFox | 389 ms | 177 ms Safari | 159 ms | 44 ms Chrome | 96 ms | 19 ms]Notes:
- The test looped a 10,000 times.
- The class occurred 1 time.
Class Versus Qualified Class
Next, we look at what to do with classes inside a container. We need a class to make the text bold. We could call the class "bold" but this might conflict with another class. So, being a thoughtful designer, we try to link the class to the container.
There's two ways to do it. We could add a CSS rule like ".container-bold" or "#container .bold" (use parent id or class the container has to narrow the class). The first option may look like it would be slower as the browser needs to look at the whole page. Also, instead of a nice and simple class name within the container, we're tacking on a lot of extra text. The CSS rule could even end up like: ".right-upper-side-article-list-bold". Good grief.
[table=tables-grid summary="Class Versus Id jQuery Performance" Browser | jQuery(".class") | jQuery("#id .class") FireFox | 1276 ms | 8174 ms Safari | 3713 ms | 4417 ms Chrome | 2722 ms | 3043 ms]Notes:
- The test looped a 10,000 times.
- The class occurred a 129 times.
- Varying the total instances of the class seemed to linearly scale the results.
Well, that wordy class name is looking pretty good now. All browsers performed the direct class lookup faster. For FireFox, it's getting close to an order of magnitude slower to qualify using an id.
Quite simply, this shows that browsers have a fast way to grab all the elements in the dom with a certain class. Qualifying it with an id (or class) means jQuery probably needs to traverse the dom structure to find the elements that have the class.
Conclusion
In general, it's best to stick to simple selectors in jQuery if the selector will be called repeatedly. So, the CSS and HTML should accommodate this by having ids where they make sense and using unique css rules across the whole page.