I read about BEM & OBCSS here and somewhere the author mentioned this:

Decoupling selector will not only increase maintainability and scalability: it will speed up the rendering. Most web browsers are caching first-level selectors. .alert and .danger will be cached but not .alert.danger!

How in particular are browsers caching these rules and why only rules with lower specificity?

I'm curious because I didn't know browsers actually cache CSS rules. Can someone give a reasonable explanation about CSS caching?

Is the speed notable for huge amounts of CSS?


I think he's referring to the browser implementation's tendency to cache the look-up of elements with a specific class. That is they keep a list of all the elements for each class. You'll often see comments about caching selectors for performance reason for long selectors. (Usually just telling the programmer not to query for the same thing multiple times in JQuery if it's expensive). It's really not something one has to think about in regards to styling though. When you insert a new node into the DOM the look-ups are fairly quick.

Depending on the page though it actually can be noticeable with Javascript queries. I've written documentation generation like software that used a lot of repetitive classes and querying complex selectors. I accidentally duplicated the same selector inside of a for loop and the program chugged until I pulled it outside of the loop. Have to use some common sense and understand that a selector look-up might be doing some work behind the scenes to match all the elements.

I'd imagine, if it's true that CSS selectors aren't memoized past the first class, that it's done for memory reasons. Storing lists of all the elements that match specific CSS rules and keeping track of them when elements are added and removed could potentially eat up a lot of memory and needless CPU on small devices. (Potentially for very little gain if the queries are infrequent).

Also every browser can implement things anyway it wants under the hood. MDN has this article: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS on some best practices. It's possible other browsers have their own guides.

Not the answer you're looking for? Browse other questions tagged or ask your own question.