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

I have read many articles about CSS performance, such as

I understand why selectors like this are bad

#social a { } 

As soon as the browser reads the first one, it will be forced to scroll through all the <a> tag elements on the page.

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

I assume that the browser creates some kind of index in order to understand which elements have a certain class (right?).

But should browsers not index which elements have a specific attribute? (e.g. name)?

My question ; Why does the CSS / element look slower when using selectors such as [title = "home"] compared to using the class? What and how does the browser work, so that the result is much slower?

+6
source share
2 answers

Browser developers optimize the most common cases. Since classes are used very often to fit styles, they should implement this as efficiently as possible. When they load in CSS, they index classes to make this possible.

Since random selectors, such as title="home" , are not used very often, they can get away from the implementation using simpler searches. This will not have a big impact on performance, because it will rarely be used.

Classes also require special handling in the browser, since an element can have several classes, for example. class="foo bar baz" . When parsing a document, the browser must break it so that it can match any of them with CSS selectors.

+3
source

Benchmark

conclusions

In most cases, an attribute selector with an unknown attribute is used, for example. [a = "b"] 'and' attribute selector with a known attribute, for example. [title = "a"] 'appeared in the "3 worst" categories. It is safe to say that you should avoid these selectors.

0
source

Source: https://habr.com/ru/post/952818/


All Articles