Is div.container faster than .container ?
You know like in jquery if you be more specific with your selectors it is faster since it iterates through less.. Is this the case with css ?
Is there a way to measure performance in css ?
Performance wise, does things like this even matter or does it all depend on text weight basically ?
I'd be happy if someone knows the answer to it, I've actually found a similar question with no certain answer.
Can CSS be more efficient if it is better specified?
In real world the speed difference would be negligible.
To be technical .container would be faster as it has fewer selectors to process.
Selectors have an inherent efficiency. The order of more to less efficient CSS selectors goes thus:
ID, e.g. #header
Class, e.g. .promo
Type, e.g. div
Adjacent sibling, e.g. h2 + p
Child, e.g. li > ul
Descendant, *e.g. ul a*
Universal, i.e. *
Attribute, e.g. [type="text"]
Pseudo-classes/-elements, e.g. a:hover
In regards to your second question:
Is there a way to measure performance in CSS ?
Steve Souders put out an online test to measure performance of CSS that can still be accessed here.
There are better ways to measure performance nowadays, but this is a quick and easy resource you can play with.
Performance wise, does things like this even matter or does it all depend on text weight basically ?
The short answer is "not really".
The long answer is, "it depends". If you are working on a simple site there is really no point to make a fuss about CSS performance other than general knowledge you may gain from best practices.
If you are creating a site with tens of thousands of DOM elements then yes, it will matter.
delta between the best case and the worst case was 50ms. In other words, consider selector performance but don’t waste too much time on it.
See: https://smacss.com/book/selectors
So I do not think it makes much sense to extend CSS rules ONLY to get a higher performance. Just consider the higher amount of network traffic, maybe worse maintainability, ...
However in the link you can read, which rules to consider without having to increase the CSS size.
If .container and div.container match exactly the same elements on your page, the first one might be even faster: If the browser evaluates .container at first, actually it would have been finished, but with div.container it has ADDITIONALLY to check, whether the element is a div.
disclaimer: I do not know how browsers really implement these things. My conclusions are based on the linked article.
Generally, the fewer the rules the better, so .container would be faster than div.container. Apart from caching, the .container gets read first, then other elements have to have the div added on as a second-level filter... unnecessary in many circumstances.
This is pretty common across engine, though there are some minor deltas.
See this article: Writing efficient CSS, which although it is from MDN (and is therefore Mozilla-geared) holds true for most of what I know about the engines in general.
Related
I have been reading for the past 1.5 hours about this and still couldn't find a concise and decisive answer.
As far as I understood browsers parse CSS selectors from right to left.
That means a long CSS selector such as this:
.card .container .businesscard .pinfo li.pinfo-box span:first-child
is one of the least efficient lines of code to ever appear here in SO.
First of all, am I right on this one?
Secondly, I am designing a rich UI using LESS, which ultimately produces this kind of mammoth selectors out of the nested designs I am coding.
What can be done to avoid this kind of selectors? Rely on classes and IDs alone? But then again what is the purpose of using LESS if you can't write nested CSS?
Your input is appreciated.
That is correct. Browsers evaluate selectors from right to left. It will try to find a span inside a li.pinfo-box and so on.
One rule of thumb to folllow when writing LESS is: do not nest more than 3-4 levels.
This will prevent your selectors from growing to big, while you will still be able to benefit from the nesting feature in LESS.
A good example of "useless" nesting is when styling lists. Sometimes I write the selectors like this:
#wrapper .blog-post ul, #wrapper .blog-post ul li
Is it really necessary to specify that the li must be inside a ul? It will probably be enough writing:
#wrapper .blog-post li
All of this is good to know. BUT: This is not the first thing to dive into when trying to optimize your sites performance. Spend some time lower the number of request or something else instead.
Selector parsing and matching is unlikely to be a big factor unless you have pretty unusual content. I would suggest using whatever is maintainable and gets the job done, up until the point where testing shows a performance issue. Then I'd get out a profiler (on OSX I'd use Instruments, but there should be a decent one available for most platforms) and attach it to the browser; if selector matching shows up high on the profile, then look into replacing slow selectors with faster ones (id selectors are definitely a good bet).
I know the performance difference is miniscule, but which is a faster CSS selector?
div.class{ }
or
.class{ }
CSS Selectors are parsed right to left, and then displayed, and the full rule is always parsed. So that would lead me to believe that .class is slightly quicker than div.class. That said, there's also the time taken to render the page, so it may depend on how many elements have that class and how complex the rule is.
Now with all of that said, check out the first answer here: https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil
The performance difference is so minuscule (if detectable at all) that it's not worth even thinking about.
Use div.class if you need some styles to only apply to div elements with that class, use .class otherwise. Base your decision on what your styling needs are, not some infinitesimal performance benefit.
Note: There are some selectors that really are (relatively) slow and might be worth changing, things like .class > *. But, even for selectors with really bad performance, and even if you're at a reasonable stage in your project to start thinking about optimizing things, there are exactly a million things you should worry about first before you get to CSS selector optimization.
I think it may depend on browser, you can check selectors here:
http://jsperf.com/jquery-performance-bn/3
In my browser (Opera 11.62) div.class was a lot faster.
.class {} selector is faster than div.class {} because in the first case browser only checks that the element has specified class, whereas in the second case it additionally has to check the element is actually a div.
I don't even remember asking this question at this point, but here's the jist:
The performance difference is minute, EXCEPT when using a JS library like jQuery. To evaluate $('.class'), jQuery checks all elements in the DOM. To evaluate $('div.class'), it only checks divs. So depending on the size of the DOM and the elements in it, the performance difference can be pretty significant.
So really, the pure CSS performance is almost exactly the same, but performance when run though a Javascript selector engine can be noticeably different. I think that is what I was aiming for when I asked this. Thanks to everyone for your comments, you all get upvotes :)
I've been reading a lot about jQuery optimization and how you can alter your selectors to cut down on the amount of DOM traversal, but I haven't heard much about CSS optimization outside of the usual minifying process. Is there any way to optimize your CSS loading/processing outside of just reducing character count and server requests?
You can definitely optimise your selectors for performance. One key point is that CSS parsers read selectors right to left, whereas javascript selector engines (like jQuery etc) read them left to right. Basically though, the general principles are the same - you want each piece of the selector to match as few elements as possible, to cut down on the DOM nodes that have to be searched in order to determine a match.
That means, just like javascript, selecting a single, bare id in CSS is the fastest way you can get to an element. Selecting everything *, or selecting based on attributes ([href*=foo]) are among the slowest.
The reading order creates a difference between optimising jQuery selectors and CSS selectors: you don't gain speed by starting with an ID. For example, if you write:
#mainContent ul li
In jQuery, you are starting by finding the element with the ID mainContent, which is very fast, then digging through it's children.
In CSS, though, you are starting with all li elements, then looking to see if they have a ul ancestor, then checking if they're inside #mainContent. Much slower.
Possible gains in speed
You should also know, however, that CSS parsing is much, much faster than javascript DOM traversal - so even when you do have lots of complex, 'slow' selectors, you're unlikely to see a huge gain in performance by optimising them. Here's a good article on the increases in performance: http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/ - the author points out that he could increase rendering time by about 20ms by creating a huge, complex stylesheet and document (6000 DOM elements, and 2000 CSS rules). For a more 'normal' page, your gains would therefore likely be less than 20ms - probably not worth the effort.
My view is that it's good to keep selector performance in mind while you're writing CSS, but don't let it make your stylesheets less readable or maintainable. In the majority of cases, it's not worth optimising an existing stylesheet, unless you can identify some selector that is really unnecessarily slow.
Here is some more good reading on the subject:
http://css-tricks.com/6386-efficiently-rendering-css/
http://code.google.com/speed/page-speed/docs/rendering.html#UseEfficientCSSSelectors
After reading some of the resources people posted in response to this question I stumbled across this (eleven year old) gem, which is still just as helpful as it was when it was written:
https://developer.mozilla.org/en/Writing_Efficient_CSS
The other big takeaway I found in my research is that you shouldn't sacrifice clean (maintainable) code or semantic best practices for CSS efficiency because the gain is so small. Still, I like my code to be clean AND efficient if at all possible, and the answers here have give me a lot to think about when writing CSS.
Yes, you can make your CSS better in terms of selector matching efficiency. By making your selectors as specific as possible, you reduce the effort needed by the HTML renderer to search the DOM for matching elements.
For example, in the cases where you know that all the spans you want to style will be direct children of the div element within your element with id #thing. it would be faster to do:
#thing > div > span.my-class
than
#thing span.my-class
because that restricts the elements that the selector has to search to find a match.
Merging stylesheets if you have multiple (remember to keep the order right)
You can also host your static content on a different server as your application (a http server optimized for serving static content), like Lighttpd
I understand that in jQuery, it's advantageous to be more specific when using selectors so that jQuery doesn't have to traverse the entire DOM to find what you're looking for. For example, $('span.description') is better than just $('.description') if I know that the description class is only ever applied to <span> elements.
Is this the case with CSS, too? Is there any specific advantage for me to use span.description { } instead of .description { }? I'm thinking in terms of speed, optimization, etc. Am I saving the browser any work by telling it exactly where to look?
This is true in CSS -
A good rule is to descend from the nearest ID.
IDs are indexed so locating them is extremely fast. There is no reason to use more than one in your selector.
Google Code- Optimize browser rendering
This answered a lot of questions I had on the subject including this one-
I hope you find it useful.
Read up on css specificity - which is the most important reason to be more or less specific with your css.
http://www.w3.org/TR/CSS2/cascade.html#specificity
As browser performance is pretty much a non-issue (except for in jquery, as you've mentioned), my guideline is to be specific when you are controlling precedence, or when you want to make something a bit more readable in your css. Over specifying can make it tricky to re-use css selectors and make things overly complicated.
Edit
This looks like a bit of a duplicate:
CSS Performance Question
it always depends on your amount of html code and the structure. It is definitely a good idea to use especially ids and appropriate selectors. (ie #nav li instead of li.nav). Since browser first load the html and then apply the css you are helping a lot.
This said, when it comes to pure css (no jquery) the difference in speed is nowadays not easy to distinguish, because the rendering engines are highly optimized - especially when it comes to applying css. So normally it shouldn't matter.
As far as I know, how specific your selectors are make very little difference on the performance.
The two areas where more specific selectors are most useful, is to reduce the risk that it's not applied where you don't want it, and to make one selector take precedence over another.
A more specific rule has precedence over a less specific rule, so:
span.myclass {}
has precedence over:
.myclass {}
(no matter what the order is in which the rules were declared)
I wondered whether or not a 'narrow' definition such as
#mytable tbody span.myclass
{
color: #ffffff;
}
is better/faster to parse than just
.myclass
{
color: #ffffff;
}
I read somewhere that narrow definitions supposedly actually have some kind of adversery effect on CSS speed, but I can't remember where and it's been a while already so I just wanted to clarify if it matters or not, and if it does, which solution is better/faster.
Thank you!
Google's Page Speed has some information regarding using efficient CSS selectors. I suggest starting there.
So (very) basically, they recommend to:
Avoid using descendant selectors, especially those that specify redundant ancestors
So your second option is the fastest.
I would opt for the former snippet and not worry about any efficiency whatsoever; unless you have a dozen or so stylesheets CSS won't be a bottleneck. The former snippet is more readable and you know exactly what you're styling, and where it belongs structurally, so when you jump back to make edits you know what to search for.
Then again if you're making global styles like a class to contain floats it would be better to keep it simple.
"Speed optimization" really shouldn't be of any concern with CSS. The difference in any modern browser is marginal, but the difference in usage is not. You should decide when to use "narrow" or "broad" selectors based on what you want to achieve, how far you want styles to cascade, where you want them to be applicable and if you need to override a broader selector.