Non-programmer readers, might want to skip this one, it’s pretty technical and relatively obscure.
Anyway, back to the thing at hand. A while ago I read Will it Optimize? by the excellent ridiculous fish. It’s a fun adventure into what code GCC recognizes and optimizes, and what it doesn’t, or can’t.
I’ll cut to the chase, using
uglifyjs -b for example minification.
This is a car that can turn left or right, and has a more general function
turn, that can turn any number of degrees.
uglifyjs does its best: 147 chars, from 228: 64%
But see how this is calling
a.turn() internally? Often seeing non-mangled names means that there’s a tweak you can make. For instance, if you eliminate public access to
d.turn, by removing its assignment to
d.turn(degrees) can now be mangled into just
b, so the compression becomes 131 chars from 220: 59% of its original size, by optimizing internal calls. It’s minor, in this instance, but add a lot of repetitive code and this difference can add up.
I was always mystified by how impressive libraries like underscore.js and reqwest would shortcut access to variables. After all, isn’t it just saving minor bytes to refer to
doc_body instead of
It eventually dawned on me: minifiers aren’t always able to alias object properties. For instance,
Which gives you a big, fat ‘Illegal invocation’, since
this isn’t the
a is run.
Now, to be clear, you could optimize to
But that isn’t fun at all, and strictly proxies
Moral of the story: minifiers don’t optimize object properties because it would be weird and hard for them to do it. When you use an object property a lot, make a variable for it yourself, and you can give that variable a descriptive name, like
aliasToDocumentPropertyX - so you can have both readability and good minification ratios.
Don’t care that much about ternary form versus
else. Local variables are reliably shortened, so don’t use single-char names unless you have very good reason, or they’re
The old wisdom about always using var for local variables is here too: if you forget, your variable name is in the global scope, so
But, if you’re writing code that aims to be invisible and uber-light for bad connections or to be thrown along with every page, it’s useful to grow an understanding of what your minifier can and can’t do.
I’m no minifier expert: if you’ve got any knowledge to share, please add it to comments or link it up. Have fun!