2

Which is better performance wise?

<a class="btn loginbtn" href="#">Login</a>​

.btn {
    background: #555 
}
.loginbtn {
    padding: 10px
}​

or

<a class="loginbtn" href="#">Login</a>​

.btn,.loginbtn {
    background: #555  
}
.loginbtn {
    padding: 10px     
}​

Since my CSS will be cached I was thinking the second one would be better.

Help me out please.

nicosantangelo
  • 13,216
  • 3
  • 33
  • 47
Famon Yaom
  • 53
  • 3
  • 1
    You can use Google Chrome, open the developer tools, select Profiles -> Collect CSS selector Profile and see which selector is faster (if it makes a difference at all). – Felix Kling Oct 29 '12 at 00:05
  • This is not a bad question, if only for the lack of specifics and references of previous research. Don't let the downvotes make you think otherwise! – Oleg Oct 29 '12 at 00:23

2 Answers2

2

You could calculate the average performance difference caused by the difference in file size as the time it would take to fetch one more TCP/IP package times the probability that it would happen because of that change (i.e. package size divived by the number of characters added).

You might get something like 10 ms * 1/1000, which would give you 10 µs.

That is such a small performance difference that you have to make the same thing a huge number of times before it's noticable.

So, you should use the one that is clearer and easier to maintain.

Personally I would go with the first option. I find it easier to see what's applied to the element if there is a single path to follow from the class names to the rules, rather than having a class scattered across several rules.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Alright thanks everyone, I'm going to use the 1st method because the second one, when it gets big, it gives me headaches. Not worth it. – Famon Yaom Oct 30 '12 at 20:48
0

The difference between the two would be very marginal, I'd be more concerned about code maintainability and maybe selector performance.

If you're really in a position where the benefit from individual bytes shaved off html adds up to something significant, you may want to check closure-stylesheets that supports CSS class renaming among other things.

Community
  • 1
  • 1
Oleg
  • 24,465
  • 8
  • 61
  • 91