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?
gzip compression will reduce identical strings to a byte or two. Use that and it's a non-issue. :)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With