• Compressing Javascript

    by  • August 30, 2011 • Articles, HTML5, Journal, Programming • 2 Comments

    To most, Javascript seems a secondary concern when writing a website, however the overall end user experience can depend a lot on Javascript, why?

    Like all web content, it has to be downloaded from a server, and this takes time. The more Javascript you have, the longer it takes to download and thus the longer it takes till the user can view your webpage.

    There are several good Javascript Compression tools available on the internet, and some have more functionality than others. All the compression tools work by a set series of operations and techniques, however they can not shrink a badly designed algorithm.

    Performance vs Space.

    The first thing to remember is that there is always a tradeoff usually between Space on disk and Performance, this is usually because the methods to reduce space normally involve increased redirection and obverscation for the Javascript runtime. Due to the advancements in Javascript runtimes in the last few years, most of the worries surrounding this issue have been negated.

    How Compressors work

    For the rest of this article I am going to talk through some of the methods employed by Javascript compressors and simple ways you can employ them in your code simply without the need to use an online compression tool and still enjoy good reduction in size.

    Remove Comments

    This may sound obvious but comments in a Javascript file have to be downloaded as well. In a production design it is recommended that all comments are removed.

    Shrink Function and Variable names

    Its always nice having long variable or function names that explain their purpose, this is in part to help reduce the amount of documentation required.

    By cleverly shrinking variable and function names hopefully to just 1 character, we can see an often dramatic reduction in size.

    Note: Care has to be taken when performing this, as sometimes links to function calls may be broken or you may accidentally reuse an existing name. This is obvious when renaming built-in functions like the Maths library:

    Math.sin(…) to m.s(…) or even s(…) will not work without a wrapper.

    Some online tools work by performing statistical analysis when renaming variables. As the best optimisation comes with variables and function names of 1 character, these are at a premium, therefore the most used 26 functions and variables are reserved for these spots.

    Use Array Literals

    Arrays are great things in Javascript however you can reduce their space by declaring them literally.

    Instead of doing for example a= new Array(); you can instead do a=[];

    Cache commonly used function calls

    For function calls to libraries or to objects, object trails exist which lead to even more characters. If the reference to the object is made multiple times then we can point the object to a variable with a shorter name, thus saving space.

    Example: Calls to the Maths library can be cached to a variable to save space:

    var m=Math,s=m.sin,c=m.cos,t=m.tan;

    Then calls can be made by calling s(…) instead of Math.sin(…)

    This may look like quite a few characters, however savings are easily made if you repeatedly call the maths libraries throughout your code.

    Link together setter statements

    This is a small space saver, normally when assigning variables in loops or such. If you are assigning multiple variables to the same value, you can link together the setter which can save space.

    Before:

    a = 0;

    b = 0;

    c = 0;

    After:

    a=b=c=0;

    Inlining & Outlining

    Inlining is a normal compiler stage optimisation. It works by injecting functions directly into the call point so that a function call is not required, and thus can shave off a few milliseconds.

    Before:

    function a() {

    b()

    }

    function b() {

    console.log(‘Do work’);

    }

    After:

    function a() {

    console.log(‘Do work’);

    }

    The space saving on this is dependant on the size of the called function and the number of times it is called. Space savings occur usually when the called function is only used once or twice, usually any more and the size of the function itself usually becomes larger than its function call wrapper.

    Outlining is the complete opposite, where we try and move code which is repeatedly used to a separate function. This means that the code is only written once and referenced by a small function call eg. a(). The scale of the savings is dependant on the amount of code being repeated and how often it is being repeated.

    WhiteSpace:

    Javascript is a bit like a brutalised C, and so we can minimise most of the syntax. This is possible as most operations end in ; We can remove nearly all whitespace and yet the parser will still happily understand the code.

    Before:

    function a(b) {

    if (b > 10) {

    console.log(‘Greater than 10’);

    }

    }

    After:

    function a(b){if(b>10){console.log(‘Greater than 10’);}}

    Remove dead code:

    During development, functions may exist that are not utilitised in the production design, normally included for debug. If the code is dead and not being used, remove it!

    Remove error messages and run time checks:

    Error messages are great while debugging, but may serve no purpose to end users, especially if output is just being piped to Console. If possible remove error messages, as displayed text is usually difficult to minimalise.

    Run time checks are implemented to check variable states or index bounds, if you are confident these may be able to be removed safely.

    Advanced compression:

    So now that you know how to do some basic optimisations, what else can be done? Note that these can only be easily be achieved by automated tools due to the complexity of implementation and analysis.

    If you have a very large Javascript codebase you can actually compress the code using something like GZip and have the code decompressed on the fly using a minimally implemented Javascript decompressor. This works by leveraging the space savings of using a text compression tool to implement the decompression algorithm.

    Javascript is a run as a virtual machine, however a program can be designed as a virtual machine itself; taking the shape of a small turing engine. By clever use of stacks and registers, variables can be removed or shuffled and functions collapsed.

     

    About

    Software engineer. Tea drinker

    http://MrPfister.com

    2 Responses to Compressing Javascript

    1. jigglypuff10
      August 30, 2011 at 1:41 pm

      i love your blog, i have it in my rss reader and always like new things coming up from it.

    2. September 19, 2011 at 5:51 pm

      You have really interesting blog, keep up posting such informative posts!

    Leave a Reply

    Your email address will not be published. Required fields are marked *