I tried putting the following JavaScript code into the Closure Compiler web interface in advanced optimization mode:
function f(some_object) {
if (some_object.foo == 1) {
console.log(some_object.bar);
} else {
alert(some_object.bar);
}
}
var my_object = {foo: 1, bar: 2};
f(my_object);
It generated the following compiled code:
var a = {b:1, a:2};
1 == a.b ? console.log(a.a) : alert(a.a);
But when I put the compiled code back into the Closure Compiler, it managed to produce an even shorter version:
console.log(2);
Does this mean I should be running the Closure Compiler multiple times on my code to make sure I'm getting the best optimization possible? Are there any potential issues with doing that?
It's very dangerous to run compiled code back through the compiler a 2nd time using ADVANCED
optimizations. The compiler does not preserve the original type annotations and the code printer will convert bracket access to dotted access where possible (obj['foo']
to obj.foo
). The output code would then quite possibly invalidate base assumptions made by the compiler.
It would be possible to rerun output code back through the compiler using SIMPLE
optimizations. However, you are very likely to see large diminishing returns with this approach. In other words: probably very little improvement.
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