Which CSS selector is faster? - css

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

Related

Are nested ids okay if necessary -- performance hit or other?

I'm using a jQuery-based framework (Kendo UI) which comes with its set of highly selective css rules.
In order to avoid the headache of my css rules clashing (and also to avoid using !important all over the place), I've nested everything in a body id -- e.g., #body-id .my-class.
However, is there a performance hit or other issue in using:
#body-id #my-other-id?
Every resource I find says, "it's pointless and makes no sense semantically." I agree, however, as I'm using the Less CSS framework, my entire CSS stylesheet will be wrapped in #body-id (for simplicity sake). Thus, it would eventually compile to #body-id #my-other-id (I'm assuming).
The jQuery selector speed is not very important, because there are other more narrow bottlenecks in your browsers JavaScript implementation.
Only if you have many, many jQuery operations like this to perform, the speed performance will be an issue
But by the way jQuery analyzes the selector (from right to left) an id with child selectors does not profit from javascript getElementById speed.
So it's more or less not important. But it may be not good style.
Check, if your CSS code is modular!
Edit
Here is a 'official' resource on performance and else
http://learn.jquery.com/performance/optimize-selectors/

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

I have been reading a lot of CSS performance articles, such as;
Efficiently Rendering CSS
Writing efficient CSS selectors
Writing efficient CSS
I get why selectors like this are bad
#social a {
}
As the browser will read a first, then is forced to loop through all the <a> tags in the page.
But why is a selector such as a[title="home"] slower than using a class?
I assume that the browser creates some sort of an index to be able to figure out what elements have a certain class (Correct?).
But shouldn't browsers also have indexed up what elements have a certain attribute? (such as title)?
My question is; why is the CSS / element look up way slower when using selectors such as a[title="home"] compared to using a class? What or how does the browser act in order that the result is so much slower?
Browser implementors optimize the most common cases. Since classes are used very frequently to match styles, they must implement this as efficiently as they can. When they load in CSS, they index the classes to make this possible.
Since random selectors like title="home" are not used very frequently, they can get away with implementing them using simpler searches. It won't have as much impact on performance, because it will rarely be used.
Classes also require special treatment in the browser, because an element may have multiple classes, e.g. class="foo bar baz". When parsing the document, the browser needs to split this up so that it can match any of them against CSS selectors.
Benchmark
Conclusions
In most cases 'attribute selector with unknown attribute, e.g. [a="b"]' and 'attribute selector with known attribute, e.g. [title="a"]' showed up in the '3 Worst' category. It's safe to say you should avoid those selectors.

CSS selector performance

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 :)

Performance of jquery selectors vs css3 selectors

I am fairly new to css3 using selectors (or simple css selectors in general) and am curious about the performance comparison of these css selectors vs jquery or javascript selectors?
Say you have something like this:
css version
#someID > div:nth-child(2n) { some css .... }
jquery version (edit)
$("#someID").children(":nth-child(even)").css({ some css ....});
Is it often faster to use the css selectors whenever you can, or use jquery selectors to adjust the css involved with an element or set of elements? Mainly when the set gets rather large. I would assume there wouldn't be much performance difference with only a handful of items?
Thanks!
jQuery's selector engine shares most of the same syntax as CSS, effectively extending the selector standard. This means you can pass most valid CSS selectors (with some exceptions) to jQuery and it'll handle them just fine.
jQuery optimizes valid CSS selectors for modern browsers that support the selectors API by passing them directly to document.querySelectorAll(). This means your jQuery selector will have almost equal performance with the equivalent CSS selector, with the only overhead being the $().css() and the selectors API calls.
For browsers that don't support the selectors API, well, it's pretty obvious that jQuery will be really slow as it has to do all the heavy lifting on its own. More importantly, it will simply fail on the exceptions that I link to above as well as any other CSS selectors a browser doesn't support.
However, with all that said, jQuery will invariably be slower, as the browser has to run through a script and evaluate it before getting a chance to apply and compute your styles.
And after all this, honestly, it's not much even if you had hundreds of items — chances are the browser is going to take longer to fetch the markup than to render the styles. If you need to do styling, and CSS supports it, why not use CSS? That's why the language was created in the first place.
Pure CSS will always be faster since it's done within the browser and optimized!
The downside is that some selectors might not be supported by the browser you're on. See http://caniuse.com/#feat=css-sel3
For me if I use jquery means that I want to put some effect on it, say like
$("#someID:nth-child(even)").css({ some css ....}).fadeIn('slow');
Apart from that you better use CSS itself, but we are barely to see the difference of it anyway, at least for a small scope system.
I've found this web that compare selector capability from different javascript framework and jquery does it quite well.
javascript framework selector test

Is there an advantage to using very specific selectors in CSS?

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)

Resources