Wednesday, March 11th, 2009

Is optimizing CSS selectors worth it?

Category: CSS, Performance

For most web sites, the possible performance gains from optimizing CSS selectors will be small, and are not worth the costs. There are some types of CSS rules and interactions with JavaScript that can make a page noticeably slower. This is where the focus should be. So I’m starting to collect real world examples of small CSS style-related issues (offsetWidth, :hover) that put the hurt on performance.

This comes from Steve Souders latest post where he surprisingly gets some data to see that optimizing selectors may not give you a huge bang for the buck.

How did this start off? Steve fills us in:

I read a series on Testing CSS Performance from Jon Sykes in three parts: part 1, part 2, and part 3. It’s fun to see how his tests evolve, so part 3 is really the one to read. This had me convinced that optimizing CSS selectors was a key step to fast pages.

But there were two things about the tests that troubled me. First, the large number of DOM elements and rules worried me. The pages contain 60,000 DOM elements and 20,000 CSS rules. This is an order of magnitude more than most pages. Pages this large make browsers behave in unusual ways (we’ll get back to that later).

A set of test cases later, and he has some data:

Why do the results from my tests suggest something different from what’s been said lately? One difference comes from looking at things at such a large scale. It’s okay to exaggerate test cases if the results are proportional to common use cases. But in this case, browsers behave differently when confronted with a 3 megabyte page with 60,000 elements and 20,000 rules. I especially noticed that my results were much different for IE 6&7. I wondered if there was a hockey stick in how IE handled CSS selectors. To investigate this I loaded the child selector and descendant selector pages with increasing number of anchors and rules, from 1000 to 20,000. The results, shown in the chart below, reveal that IE hits a cliff around 18,000 rules. But when IE 6&7 work on a page that is closer to reality, as in my tests, they’re actually the fastest performers.

I am curious to see the difference between the role of CSS selectors in a one pass web page, compared to applying rules to content changes in an Ajax application. Imagine Gmail adding a new message to the DOM…. how does the CSS work change there?

Posted by Dion Almaer at 8:44 am

4.4 rating from 26 votes


Comments feed TrackBack URI

This is about internal browser use of selectors for styling, right? I first assumed that we (as usual) were talking about JavaScript use of selectors for reading and altering the DOM.

Comment by Nosredna — March 11, 2009

Here’s a Bug report for Firefox:

Comment by TNO — March 11, 2009

Leave a comment

You must be logged in to post a comment.