CSS selector performance

I know the performance difference is minimal, but is it a faster CSS selector?

div.class{ } 

or

 .class{ } 
+4
source share
5 answers

The difference in performance is so slight (if at all detected) that you should not even think about.

Use div.class , if you need some styles that apply only to div elements with this class, use .class otherwise. Begin your decision about what your design needs are, not some infinitely small advantage.

Note. There are several selectors that are really (relatively) slow and can be changed, for example, .class > * . But even for selectors with very poor characteristics, and even if you are at a reasonable stage in your project to start thinking about optimizing things, there are only a million things that you should worry about before moving on to optimizing the CSS selector.

+4
source

CSS selectors are parsed from right to left and then displayed, and the complete rule is always parsed. So I would be lucky that .class little faster than div.class . However, it also takes time to render the page, so this may depend on how many elements this class has and how complicated the rule is.

Now with everything that said, check out the first answer here: https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil

+4
source

I think it may be browser dependent, here you can check the selector: http://jsperf.com/jquery-performance-bn/3

In my browser (Opera 11.62) div.class was much faster.

+2
source
Selector

.class {} faster than div.class {} , because in the first case, the browser only checks that the element has the specified class, while in the second case, it must additionally check the element actually a div .

0
source

I don’t even remember to ask this question at the moment, but here's jist:

The difference in performance is a minute, EXCEPT when using a JS library such as jQuery. To evaluate $ ('. Class'), jQuery checks all the elements in the DOM. To evaluate $ ('div.class'), it only checks divs. Therefore, depending on the size of the DOM and the elements in it, the performance difference can be quite significant.

So, the pure CSS performance is almost the same, but the performance at startup, although the Javascript selection mechanism may be noticeably different. I think this is what I aspired to when I asked about it. Thank you all for your comments, you all get upvotes :)

0
source

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


All Articles