Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript minification of string literals?

I was looking over some of our JavaScript compression and noticed that no strings that aren't object property names are minified into variables.

For example, let's say I have these two pieces of code in my script:

alert("Wrong answer");
alert("Wrong answer buddy");

The minification we get from YUI and Closure, if I'm not mistaken, is:

alert("Wrong answer");alert("Wrong answer buddy");

I would think the resulting minification would look like this:

var a="Wrong answer";alert(a);alert(a+" buddy");

Do any minification tools do this? What's stopping our tools from doing this?

like image 468
CantSleepAgain Avatar asked Jul 21 '10 03:07

CantSleepAgain


3 Answers

gzip compression will reduce identical strings to a byte or two. Use that and it's a non-issue. :)

like image 62
Dagg Nabbit Avatar answered Sep 29 '22 13:09

Dagg Nabbit


If I were to hazard a guess, I would say that it is because the compiler cannot tell when it would be more optimal to break out your strings into variables and concatenate them. (And, as such things go, it falls under the heading of micro-optimization in the first place.)

For example, the following code:

if (test_case==="He fell down a well") {
    var i=my_object_array.length-1;
    while(i>=0) {
        my_object_array[i].say("He fell down a well did he Lassie?");
        i--;
    }
}

Might be re-rendered by your theoretical compiler as:

var x="He fell down a well";
if (a===x) {
    var i=b.length-1;
    while(i>=0) {
        b[i].say(x+" did he Lassie?");
        i--;
    }
}

... which would of course, increase the time it takes for the while loop to complete its work.

Of course, a slightly more intelligent compiler might recognize that trap and optimize still further:

var x="He fell down a well";
var x1=x+" did he Lassie?";
if (a===x) {
    var i=b.length-1;
    while(i>=0) {
        b[i].say(x1);
        i--;
    }
}

Either way though, a good javascript compiler, to my mind, optimizes the code first for performance, and only secondarily for character count. As this is an optimization primarily for character count improvement I think that there probably simply has not been enough demand for it to warrant the time of the people who maintain Closure and the YUI Compressor.

like image 35
Sean Vieira Avatar answered Sep 29 '22 13:09

Sean Vieira


The compression tools have their limits and you found one. You should create your own variables for the strings, then the tools will compress the variable names.

Eg
var msg_wrong = "Wrong answer",
    msg_very_wrong = msg_wrong + "!!!";
alert (msg_wrong);
alert (msg_very_wrong);


// "msg_wrong" and "msg_very_wrong" variable names will be compressed
like image 38
Larry K Avatar answered Sep 29 '22 15:09

Larry K