Do long CSS class names have an effect on performance? - css

I am building a JS script with a theme included, in order to run multiple themes each classname has a prefix - this however makes the classnames somewhat long.
I also have CSS rules depending on wether or not the element has more classnames in order to provide special effects.
My question is will longer CSS classnames have an effect on performance, or will only wrong/faulty/inefficient use of selectors slow down performance?

Long class names will definitely have an impact on performance. For one, there will be more stuff to be transferred and parsed. Will they have a measurable impact however? Probably not. The transfer only happens once, thanks to caching and the impact on parsing will likely be negligible compared to for instance rendering.
In general, you should only start thinking about such performance optimizations if you start running into performance problems. Its better to use expressive names to improve readability of your css (the same goes for any kind of code) before optimizing for possible performance issues.
For selectors, they will likely have a higher impact on performance, as depending on the complexity of a selector and the size of your DOM, a considerable (considerable compared to long class names) amount of code might have to be executed. However, again try to make the most readable/understandable selector and only start optimizing it if there is a measurable performance impact (you can use firebug or chrome's developer tools for profiling).

will longer CSS classnames have an effect on performance, or will only wrong/faulty/inefficient use of selectors slow down performance?
longer classnames? - I don't think it matters, I prefer shorter but with some applications or plugins it's not possible - PageSpeed and Y!Slow nor any other performance recommendation sites I've visited, mention the length of classname as being an issue - But definitely the more efficient the whole selector, the better the performance

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/

Is there much performance gain from using as few CSS classes as possible?

Recently I've come upon a mobile UI kit which used very long CSS class names, seemingly instead of utilizing multiple class names and CSS inheritance (e.g. ".container-element-subelement"). Is there much performance gain from this? Because it sounds like a nightmare to have to maintain those stylesheets later.
Performance gain from what you referred to should be negligible (of course, depends on the user's hardware, the page size, and browser).
There was some discussion on this here: CSS child selector performance vs. class bloat
Well the answer is YES it will affect performance.
If you use a .css framework just for a little option (like loading all jquery-ui, just to make rounded corner on a single div, ... non-sence.
also, take it more deeply, comparing :
.this-verry-long-way-too-long-css-selector-to-do-something {}
and
.thisselector {}
45 caracters difference = many bytes difference,
multiply by numbers of too-long-selector-names,
multiply by number of times your .css file is sended by your server
= bandwidth
There is that tool you can use : yslow 'firefox plugin' to help you study and tweek .css performance
EDIT : ok, i understand your question.
Then, it's a DOM engine relevant and good question.
So, i think a DOM engine will perform better if stacking basic simple selectors.
You can use Chrome Developer Tools' Selector Profiler (in the Profiles panel) to profile the time it takes a browser to process selectors in your page (match + apply styles to the matching elements.)
There a documentation here : http://moduscreate.com/efficient-dom-and-css/
carry on

Implementing css behavior attribute in LESS Mixins

I've been playing around with LESS for a little bit to see about converting the website I manage at work over.
When I was learning about the behavior: url(...blah) ability of css I thought I had read that it was best to use that as little as possible for performance reasons (I now can't find that anywhere so not sure if that's still valid).
So with that assumption in mind I am a little apprehensive about converting that CSS into a LESS Mixin. Is this truly a performance hit or can I safely do this without being concerned about a slow down of the site's UI?
an example of what I'd be converting...
.FullRoundedBorder
{
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
-khtml-border-radius: 8px;
border-radius: 8px;
behavior: url(/Content/CSS/PIE/PIE.htc);
}
For those that haven't seen it PIE is an awesome plugin for rounded border cross browser functionality (mainly it fixes IE 6-8).
The use of the 'behavior' property itself is not a major performance concern -- you may have been thinking of 'expression' which is indeed very bad for performance.
However, you do need to examine the performance of the specific .htc that you pull in. Essentially .htc files are pieces of JavaScript that are executed when the CSS selector matches an element. This means that the more elements that are matched by your selector, the more times that script will run.
In the case of a complex script like PIE.htc, it is very easy to use it on too many elements resulting in a noticeable delay while it runs. Like any other script, you need to be deliberate about how widely you apply it, and of course test the performance of your site after applying it.
My experience with PIE.htc is that using it on about 15 elements or fewer is not noticeable, but beyond that you start noticing a delay. There are often things you can do to lessen the impact, such as using -pie-lazy-init.
Yes, PIE will slow down the UI in IE6-8. The more effects you stack on, the greater the impact. It should not affect other browsers.
I used PIE in a (big!) project last year to get some effects in IE6-8, but upon revisiting that project this year I decided to scrap all use of PIE. I found it to be flaky and inconsistent -- it would randomly fail to render a "Pay Now" button for instance. IE users would therefore be randomly incapable of paying their bill. I switched back to Modernizr with an image fallback for < IE 9. The moral of the story is: PIE seems great, but use it sparingly and only for non critical elements. It's difficult to debug when it goes wrong.
You can also easily try it and just disable it if you find your UI is too slow with it. If your mixins are good, it should only be a few lines of code.
I've worked extensively with Less. I like how it breaks large CSS into more logical and readable chunks. A few things to consider:
1) Will you be processing the Less server side or client side? I'm more of a proponent of putting fewer load on the UI/Browser because you simply don't have control over what kind of machine, browser the user is running and it adds more points of failure in your UI implementation. Simpler is always better. If your UI is for a small audience then you should see no performance hit. In most cases I will use Less when the plain CSS would be too large to easily maintain and read and thus accept a slight performance hit, especially if the user base is trivial. For high traffic sites, I would probably rewrite or convert back to CSS and publish the straight CSS.
2) Is Less really necessary? Are you loading a bunch of translation code or running an extra process on your server just so you don't have to write a few extra lines of CSS??? This is not justification enough in my Opinion. I often question the use of other "make your life easy" libraries/tools like JQuery, when i see a developer loading an entire library just because they didn't want to write "getElementByID()" pure native JavaScript.
Everything has it's place and it's use in a project/implementation. I suggest making a list of the benefits and then eliminating those that can be readily implemented with native browser features(plain CSS and JS). Smaller and lighter is always better and faster, especially if you're also running on mobile and legacy platforms.
I hope this helped.

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

Is there more to optimizing CSS than minimizing character count?

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

Resources