SlimIt 0.4 released: block braces removal

by Ruslan Spivak on May 12, 2011

SlimIt 0.4 is released and it features block braces removal during minification process.

If a block statement contains only one source element then curly braces around that statement are removed by SlimIt:

with (obj) {
    a = b;
}

after minification will become:

with(obj)a=b;

And

if (true) {
    x = 1;
} else {
    x = 0;
}

will become

if(true)x=1;else x=0;

There is one case where braces removal gets tricky. Take a look at the following JavaScript code:

if ( obj ) {
    for ( n in obj ) {
        if ( v === false) {
            break;
        }
    }
} else {
    for ( ; i < l; ) {
        if ( nv === false ) {
            break;
        }
    }
}

If we blindly remove all block braces result will be the following (output is indented and formatted to illustrate the point):

if (obj)
    for (n in obj)
        if (v === false)
            break;
else
    for (; i < l; )
        if (nv === false)
            break;

but it will be interpreted by a JavaScript parser as

if (obj)
    for (n in obj)
        if (v === false)
            break;
        else
            for (; i < l; )
                if (nv === false)
                    break;

because else part will be associated with the closest if and that’s not what was described by the original pre-miniified source code. Because of that the minifier will convert such construct to the following form to avoid ambiguity but still performing minification where possible (indented for illustration purpose):

if (obj) {
    for (n in obj)
        if (v === false)
            break;
} else
    for (; i < l; )
        if (nv === false)
            break;

And this is how it’ll look like in minified form:

if(obj){for(n in obj)if(v===false)break;}else for(;i<l;)if(nv===false)break;')

Here are some new numbers for jsmin, rJSmin, and SlimIt minification of jQuery 1.6.1:

jQuery 1.6.1 (bytes) jsmin rJSmin SlimIt
234,995 134,819 134,215 132,336

P.S: After minification by SlimIt I ran a test suite that comes with jQuery against the minified version and got the same results as with official minified version.

If you enjoyed this post why not subscribe via email or my RSS feed and get the latest updates immediately. You can also follow me on GitHub or Twitter.

Speak your mind

Previous post:

Next post: