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 :)
Related
Which selector is faster: input[type='text'] or [type='text']?
In jQuery the second one but in CSS?
I think that still [type='sth'] because is "less specific and shorter to read" by browser.
CSS performance check
It depends on browser.
Both are faster, the difference is that [type='sth'] will be applied to all elements including non-input tags.
<link type="sth">
This tag will be applied with your class.
This question is pointless - the answer would have to include a specific version of a specific browser, a specific HTML file, specific css file, specific Javascript and the exact scenario. Also, you would have to define "faster": faster to parse? faster to query from the document? faster to guess if a specific tag fits the rule?
Years ago, when browsers were simple, such made some sense. Modern browsers have optimizations that rival those of modern databases or compilers, and this makes microbenchmarking a moot point. There could be any number of fast paths, exceptions, corner cases, shortcuts for common cases that make such simple reasoning impossible.
In CSS, there is no way to detect which one is faster, but you can know which CSS property values are the most relevant to an element :
https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
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.
I hate them, it defies the cascading nature of CSS, and if you don't use them with care you end up in a loop of adding more !important.
But I want to know are they bad for performance?
EDIT
From the (fast) replies I can conclude it won't have a (significant) impact on performance.
But it's nice to know, even if it's just as an extra argument for discouraging others ;).
EDIT 2
BoltClock pointed out that if there are 2 !important declarations the specs says it will pick the most specific one.
It shouldn't have any discernible effects on performance. Seeing Firefox's CSS parser at /source/layout/style/nsCSSDataBlock.cpp#572 and I think that is the relevant routine, handling overwriting of CSS rules.
It just seems to be a simple check for "important".
if (aIsImportant) {
if (!HasImportantBit(aPropID))
changed = PR_TRUE;
SetImportantBit(aPropID);
} else {
// ...
}
Also, comments at source/layout/style/nsCSSDataBlock.h#219
/**
* Transfer the state for |aPropID| (which may be a shorthand)
* from |aFromBlock| to this block. The property being transferred
* is !important if |aIsImportant| is true, and should replace an
* existing !important property regardless of its own importance
* if |aOverrideImportant| is true.
*
* ...
*/
Firefox uses a top down parser written manually. In both cases each
CSS file is parsed into a StyleSheet object, each object contains CSS
rules.
Firefox then creates style context trees which contain the end values
(after applying all rules in the right order)
From: http://taligarsiel.com/Projects/howbrowserswork1.htm#CSS_parsing
Now, you can easily see, in such as case with the Object Model described above, the parser can mark the rules affected by the !important easily, without much of a subsequent cost. Performance degradation is not a good argument against !important.
However, maintainability does take a hit (as other answers mentioned), which might be your only argument against them.
I don't think that !important is inherently bad in terms of how quickly the browser matches rules (it does not form part of the selector, only part of the declaration)
However, as has already been stated, it will reduce the maintainability of your code, and thus likely cause it to grow unnecessarily in size due to future changes. The usage of !important would also likely reduce developer performance.
If you were being really picky, you could also say that !important adds 11 extra bytes to your CSS file, this isn't really much, but I guess if you have a fair few !importants in your stylesheet it could add up.
Just my thoughts, unfortunately I couldn't find any benchmarks on how !important could affect performance.
!important has its place. Trust me on that one. It's saved me many times and is often more useful as a short-term solution, before a longer and more elegant method to your problem can be found.
However, like most things, it's been abused, but there's no need to worry about 'performance'. I'll bet one small 1x1 GIF has more of a performance hit on a web page than !important would.
If you want to optimize your pages, there are many more !important routes to take ;) ;)
What's going on here behind the scenes is that as your CSS is being processed, the browser reads it, encounters an !important attribute, and the browser goes back to apply the styles defined by !important. This extra process might seem like a small additional step, but if you are serving up many requests then you will take a hit in performance. (Source)
Using !important in your CSS usually means developer narcissistic & selfish or lazy. Respect the devs to come...
The thinking of a developer when using !important:
My rocking CSS is not working... grrrr.
What should I do now??
And then !important yeah.... now it's working fine.
However its not a good approach to use !important just because we did not manage the CSS well. It creates lots of design issues -- which are worse than performance issues -- but it also forces us to use many extra lines of code since we are overriding other properties with !important and our CSS becomes cluttered with useless code. What we should do instead is first manage the CSS very well, and not let properties override one another.
We can use !important. But use it sparingly and only when there is no other way out.
I agree with you on not using it because it's bad practice, regardless of performance. On those grounds alone, I'd avoid using !important wherever possible.
But on the question of performance: No, it shouldn't be noticeable. It might have some effect, but it should be so tiny you should never notice it, nor should you worry about it.
If it is significant enough to be noticable then you've likely got bigger problems in your code than just !important. Simple use of a normal syntax element of the core languages you're using is never going to be a performance issue.
Let me answer your question with a retorical question in return; an angle that you probably didn't consider: Which browser do you mean?
Each browser obviously has its own rendering engine, with its own optimisations. So the question now becomes: what are the performance implications in each browser? Perhaps !important performs badly in one browser but really well in another? And perhaps in the next versions, it'll be the other way round?
I guess my point here is that we as web developers shouldn't think about (or need to think about) the performance implications of individual syntax constructs of the languages we're using. We should use those syntax constructs because they're the right way to achieve what we want to do not because of how they perform.
Performance questions should be asked in conjunction with the use of profilers to analyse where the pinch-points are in your system. Fix the things that are truly slowing you down first. There are almost certain to be far far bigger issues for you to fix before you get down to the level of individual CSS constructs.
It does not noticeably affect performance. It does however reduce the maintainability of your code, and therefore is likely to degrade performance in the long run.
Having had to use !important several times before, I have personally noticed no demonstrable performance hit when using it.
As a note see the answer to this stack question for a reason you might want to use !important.
Also I'll mention something that everyone else has failed to mention. !important is the only way to override inline css short of writing a javascript function (which will effect your performance if even only a little bit). So it could actually save you some performance time if you need to override inline css.
hmm... !important or !!important?
Let's go through this step by step:
The Parser has to check for !important for each property, regardless of whether you use it or not - so performance difference here is 0
When overwriting a property, the parser has to check whether the property being overwritten is !important or not - so performance difference here is 0 again
If the property being overwritten is !!important, it has to overwrite the property - performance hit of -1 for not using !important
If the property being overwritten is !important, it skips overwriting the property - performance boost of +1 for using !important
If the new property is !important, the parse has to overwrite it regardless of the property being overwritten is !important or !!important - performance difference 0 again
So I guess !important actually has better performance as it can help parser skip many properties that it won't skip otherwise.
and as #ryan mentions below, the only way to override inline css and avoid using javascript... so another way to avoid an unnecessary performance hit
hmm... turns out out that !important is important
and also,
using !important saves a lot of time for a developer
sometimes saves you from redesigning the whole css
sometimes html or the parent css file is not in your control, so it saves your life there
obviously prevents !important elements from being accidentally overwritten by other !!important elements
and sometimes browsers just don't pick the right properties, without being too specific in selectors, so using !important really becomes important and saves you from writing tonnes of specific css selectors in your css. so i guess even if you use more bytes for writing !important, it could save you bytes in other places. and we all know, css selectors can get messy.
So I guess using !important can make developers happy, and I think that's very important :D
I can't foresee !important impeding performance, not inherently anyway. If, however, your CSS is riddled with !important, that indicates that you've been over qualifying selectors and being too specific and you've run out of parents, or qualifiers to add specificity. Consequently, your CSS will have become bloated (which will impede performance) and difficult to maintain.
If you want to write efficient CSS then you want to be only as specific as you need to be and write modular CSS. It's advisable to refrain from using IDs (with hashes), chaining selectors, or qualifying selectors.
IDs prefixed with # in CSS are viciously specific, to the point where 255 classes won't override an id (fiddle by: #Faust). ID's have a deeper routed problem too though, they have to be unique, this means you can't re-use them for duplicate styles, so you end up writing linear css with repeating styles. The repercussion of doing this will vary project to project, depending on scale, but maintainability will suffer immensely and in edge cases, performance too.
How can you add specificity without !important, chaining, qualifying, or IDs (namely #)
HTML
<div class="eg1-foo">
<p class="eg1-bar">foobar</p>
</div>
<div id="eg2-foo">
<p id="eg2-bar">foobar</p>
</div>
<div class="eg3-foo">
<p class="eg3-foo">foobar</p>
</div>
CSS
.eg1-foo {
color: blue;
}
.eg1-bar {
color: red;
}
[id='eg2-foo'] {
color: blue;
}
[id='eg2-bar'] {
color: red;
}
.eg3-foo {
color: blue;
}
.eg3-foo.eg3-foo {
color: red;
}
JSFiddle
Okay, so how does that work?
The first and second examples work the same, the first is literally a class, and the second is the attribute selector. Classes and Attribute selectors have identical specificity. .eg1/2-bar doesn't inherit its color from .eg1/2-foo because it has its own rule.
The third example looks like qualifying or chaining selectors, but it's neither. Chaining is when you prefix selectors with parents, ancestors, and so on; this adds specificity. Qualifying is similar, but you define the element the selector's applying to. qualifying: ul.class and chaining: ul .class
I'm not sure what you'd call this technique, but the behavior is intentional and is documented by W3C
Repeated occurrances of the same simple selector are allowed and
do increase specificity.
What happens when the specificity between two rules is identical?
As #BoltClock pointed out, If there's multiple !important declarations then
spec dictates that the most specific one should take precedence.
In the example below, both .foo and .bar have identical specificity, so the behavior fallsback to the cascading nature of CSS, whereby the last rule declared in CSS claims precedence i.e. .foo.
HTML
<div>
<p class="foo bar">foobar</p>
</div>
CSS
.bar {
color: blue !important;
}
.foo {
color: red !important;
}
JSFiddle
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)