« Back to home

JavaScript module patterns and code size

A few days ago I did some code refactoring:

File Bytes before Bytes after
requestform.js 41491 45884
requestform-min.js 23565 21058

What’s going on here? Well, the code is quite old, and was written using the direct assignment method of global abatement. Now that I’m more comfortable with JavaScript, I rewrote the code to use the revealing module pattern.

The direct assignment module pattern is simple to understand, but the code ended up with ‘this.’ and the name of the object everywhere. While the object name was short, repeating it many times bloated the code size.

So why did the refactored source file end up bigger? Well, I use JSLint, so I end up with a single huge var declaration for all of the object’s members. All the methods end up indented one more level when using the new module pattern. And of course, the indentation is done using spaces. For a less misleading impression, I compared the code size minus all whitespace. Even with the new pattern’s requirement to re-list all public methods, the non-whitespace parts of the code ended up around 2KB smaller, thanks to removing all the ‘this’s and object names.

Obviously all the indentation whitespace is removed during minimization, so the ‘-min’ version of the refactored code should end up no larger after refactoring. In fact, it ends up significantly smaller. The gain is better than the gain from removing all those object names. This is because I’m minifying using Google’s Closure compiler. Using the revealing module pattern, the internal names of public methods are never visible, and don’t have to match the public names. This allows the compiler to rename all the functions within the module to impenetrable single character names. In addition if you use unobtrusive JavaScript, as mentioned in the previous posting, then your callbacks don’t have to be visible. That means the compiler can rename all of those to shorter names too.

This is the additional benefit to unobtrusive JavaScript that I alluded to: while the ‘source’ JavaScript code is more verbose, the compiled/minified version will generally end up smaller.