Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are selectors such as a[title="home"] slower than using class?

I have been reading a lot of CSS performance articles, such as;

  • Efficiently Rendering CSS
  • Writing efficient CSS selectors
  • Writing efficient CSS

I get why selectors like this are bad

#social a {
}

As the browser will read a first, then is forced to loop through all the <a> tags in the page.

But why is a selector such as a[title="home"] slower than using a class?

I assume that the browser creates some sort of an index to be able to figure out what elements have a certain class (Correct?).

But shouldn't browsers also have indexed up what elements have a certain attribute? (such as title)?

My question is; why is the CSS / element look up way slower when using selectors such as a[title="home"] compared to using a class? What or how does the browser act in order that the result is so much slower?

like image 995
corgrath Avatar asked Aug 30 '13 09:08

corgrath


1 Answers

Browser implementors optimize the most common cases. Since classes are used very frequently to match styles, they must implement this as efficiently as they can. When they load in CSS, they index the classes to make this possible.

Since random selectors like title="home" are not used very frequently, they can get away with implementing them using simpler searches. It won't have as much impact on performance, because it will rarely be used.

Classes also require special treatment in the browser, because an element may have multiple classes, e.g. class="foo bar baz". When parsing the document, the browser needs to split this up so that it can match any of them against CSS selectors.

like image 192
Barmar Avatar answered Oct 24 '22 13:10

Barmar