In this post I will do a quick comparison between the Closure Compiler and UglifyJS2.
I think UglifyJS is an invaluable tool, but how does it compare to the Closure Compiler?
Let's start with a basic sample application.
All this application does is create a greeting and alert the user of the greeting. This is an important point, but I will get back to that later.
After running the code through Uglify I end up with the following minified code:
I am trying to be as aggressive as possible here with my Uglify configuration as seen below:
After minification we see that white space has been removed and the greeter function has been renamed to a single character name.
All things considered, this is a pretty good size reduction.
Next let's see how the results from Uglify compare to the Closure Compiler.
The Closure Compiler comes with three compilation levels (WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS and ADVANCED_OPTIMIZATIONS)
The compilation levels dictate how aggressively the compiler will optimize your code.
Let's run the sample code through all three levels.
WHITESPACE_ONLYAs the name suggests we should not expect great things here. Sure enough the result is nothing more than white space removal.
In theory we should see an improvement from raising the compilation level to SIMPLE_OPTIMIZATION.However in this particular example we don't see a change from the WHITESPACE_ONLY run.
In general you would see more of a difference between SIMPLE_OPTIMIZATION and WHITESPACE_ONLY. However in this case the code is so simple that there isn't much of a difference.
So far we see that the output from Uglify is actually better. This is mainly because I've enabled some of Uglify's aggressive options.
Closure compiler doesn't really start to get interesting until you enable ADVANCED_OPTIMIZATION. This is where you start to see some amazing results though.
Take a look at the Closure compiled output of the original sample:
As you can tell this is drastically better than any of the other results. Basically the Closure compiler rewrote the original code to something much smaller. This goes far beyond simple minification since the original code is actually rewritten. Closure was able to analyze the original code and conclude that the outcome is always an alert of the string “Hello there”.
All the other code in between was removed through function flattening and inlining.
It's worth pointing out that these impressive results come at the cost of potentially breaking your application if you're not careful. In some cases Closure might go too far. This is why Closure compiler is often referred to as an export tool.
It's important that you write your code with the Closure compiler in mind in order to benefit from it.
I have another article with some advice on how to successfully use Closure.