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.
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.
|FireFox||389 ms||177 ms|
|Safari||159 ms||44 ms|
|Chrome||96 ms||19 ms|
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.
|FireFox||1276 ms||8174 ms|
|Safari||3713 ms||4417 ms|
|Chrome||2722 ms||3043 ms|
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.
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.