Sorting CSS to reduce gzip file sizes?

September 2nd, 2009. Tagged: CSS, performance, yui

Yesterday I came across this post (via Ajaxian), it talks about how you might be able to end up with smaller file sizes (after gzipping) if you help gzip a little bit by sorting the CSS properties and values in stylesheets, so they are as similar and close to each other as possible.

Now obviously it's not easy to do a safe sorting, there's many edge cases to be taken care of, but the question before diving into safeness is - is it really worth it?

In attempt to answer that I did a very simple CSS parser in JavaScript that will sort the properties and values, then I tested with a few files.

Long story short - it's probably not worth it. But if you want to help, please use the online tool and report if you see a considerable benefit for your own stylesheets.

How it works

Again, bear in mind this is not safe to do, your pages might look different before and after optimization. This is just a test if alphabetizing is really worth it in terms of gzipped filesize.

Before:

b {
  b: b c a;
  a: a b c;
}

a {
  a: a;
}

After

b {
  a: a b c;
  b: a b c;
}
a {
  a: a;
}

As you can see, order of selectors is preserved, properties within each CSS block are sorted and their values are sorted too.

Help by testing your CSS

Since the original question was - is it worth modifying YUI Compressor to sort properties and values, you can help by following these two steps:

  1. minify your real-life CSS with YUI compressor (online version here) and then
  2. paste the result in my parser/sorter tool to see if you can gain much after compression.

Please share your results in the comments section of this post.

Results so far?

I tested with two files well under 10K and the results were ever-so-slightly negative - the results were 0.05% bigger.
Tested also with a few files over 10K and the results were 1.5% savings. Hardly worth it. But I hope someone can prove me wrong and show cases where alphabetizing can be well worth it. After all, the sweetest optimization is the one you don't have to do, but your build process can manage by itself ;)

Tell your friends about this post: Facebook, Twitter, Google+

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile, hit me up on twitter @stoyanstefanov