Testing CSS Performance

Jim brought up an interesting discussion yesterday about CSS performance and if child selectors are inefficient.

The basis for the thinking is something Dave Hyatt mentioned in a Shaun Inman post. Basically that child selectors are ineffecient because they actually work right to left rather than left to right to find the element you’re referring to.

So this…

  2. body table tr td.myTestClass{
  3.   background-color: red;
  4. }

is allegedly considerably less efficient than…

  2. .myTestClass{
  3.   background-color: red;
  4. }

Now I figured it would be interesting to see if I could throw together a quick test that might show this difference. Testing and benchmarking CSS is not something I’ve seen very much of, so I assumed it was either A: Virtually impossible, B: A silly idea, C: Boring, but that never stopped me before, so I headed to the whiteboard.

Thought Process

At the very top of the a HTML I would use Javascript to create a timestamp, this is the starting timer for everything.

I would then have a function on a setInterval so it loops, the function checks a dom element using getElementById, it checks to see if that node is there, if it is it checks to see if the node has the style applied to it, if it does it fires a new timestamp marks the difference between the start and the end and then writes that out (I wrote it out to the page, as I was initially using console.debug, but that’s not very cross browser compatible).

I then have 2 css declarations, one with lots of child selectors and one direct class reference.

I then have a 20 x 1000 table created using PHP loops.

The CSS is applied to two of the table cells. Next to each other.

The null hypothesis is that running these both in the same page, the child selector way will take longer to be seen as being “red” than the direct style.

The test can be viewed at:


There is almost no difference. Funnily enough there’s a fairly consistent 7ms difference which I guess is either the time it takes to do the tests in order, or it’s the fact that the second node is further down the dom.

So no difference. Bit of an anti-climax.

Why is there no difference

I have a couple of ideas:

The test is fundamentally flawed in a way that’s not immediately obvious to me.

The two CSS that I’m comparing don’t display the issue, maybe I need different example.

Maybe the browser does everything CSS then renders the page, so 1 might be happening faster, I just can’t test it. (I’m going to make a different test where I have two pages with lots of each example and I test overall load time rather than individual node styling time).

Other stuff

One thing I did find that was interesting. During my testing and debugging I added an onload timestamp as well. I was getting the “Node is red” timestamp, before the onload. Which I thought was interesting.

More to come.

About this entry