开发者

Are CSS selectors a big performance hit?

I have a web application with bunch of HTML code. There are some style-attributes that I can't get rid of, but I was wondering if it's worth the cleanness to get rid of开发者_JS百科 class-names and use CSS selectors instead. Do CSS selectors perform slowly?

I'm talking about replacing class-name selectors such as .example with more complex selectors like #example div > div:nth-child(3) > p


Take a look at this article to see a graph on this. I don't know how exact this benchmark is, but it seems child selectors are indeed slower, but you're not going to find any visible gains by avoiding child selectors.. this is a micro optimization that has "diminishing returns" written all over it.


The performance hit is tiny.


Here you can find an interesting blog post on the argument with examples and tests of CSS selectors performances on most common browsers:

http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/

This is the conclusion of the author:

Based on these tests I have the following hypothesis: 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.


The browser matches from right to left, and any non-specific tags will cause more of a performance hit.*

1–Slower:

.foo p

2–Faster

.foo p.bar

What happens is in the first example, the browser matches ALL paragraphs, then narrows it down to those whose ancestor has the foo class.

In the second example, the browser matches all elements that have the bar class, then matches the subset that are paragraphs, then the subset whose ancestor has the foo class.

One would generally expect the initial set of the second example to be smaller than that of the first example.

*Bear in mind that the hit will really only become apparent with poorly-crafted CSS on pages that are very large (megs) and/or have many, many elements (e.g., hundreds of spans or divs). Small pages with only a few number of elements will not see a real—if any—performance hit, even with poorly-written CSS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜