closure-compiler
closure-compiler copied to clipboard
variable could be assigned at declaration
I believe the output from advanced mode could be (mildly) optimised from var a;a=window.setTimeout;
to var a=window.setTimeout;
without causing any issues.
The full input file was:
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// ==/ClosureCompiler==
function hello(name) {
alert('Hello, ' + name);
}
var timer;
if( true ){ // or a truthy variable
timer = window['setTimeout'];
}
timer(function(){ hello('New user'); },100);
timer(function(){ hello('something else'); },100);
producing
var a;a=window.setTimeout;a(function(){alert("Hello, New user")},100);a(function(){alert("Hello, something else")},100);
This definitely sounds like a safe optimization to make. Unfortunately, there are so many safe optimziations that would improve code-size that we don't generally have time to act on them all. I think Nick Santos used to jokingly refer people to the Full Employment Theorem on this topic, which basically says there are always more optimizations to write than there is time to implement them.
If this is something you'd like to work on yourself, I'd guess it can be implemented as a "Peephole Optimization".