How does the Closure Compiler use type information to compile to speed JavaScript?

The Google Closure Compiler compiles more efficient JavaScript. I can present some simple examples, such as the Closure Compiler, which reduce the call stack by calling functions directly or replacing constants with literals. But the documentation goes further, saying:

"The Closure compiler can use data type information about JavaScript variables to provide advanced optimizations and warnings."

My understanding was that typed languages ​​had two advantages: 1) type checking can catch errors during compilation - I can see how the Closure Compiler can mimic this behavior - and 2) the program actually runs faster because it compiled for another language (e.g. Java bytecode in Java). JavaScript still works with the Closure Compiler. How can it be optimized based on type information?

+4
source share
3 answers

One example is the disambiguateProperties function described at http://closuretools.blogspot.com/2011/01/property-by-any-other-name-part-3.html

, . . , x.foo() , , foo:

X1.prototype.foo = function() {
  // Lots and lots of code...
};


X2.prototype.foo = function() {
  // Lots and lots of code...
};

, x, long foo , . , x X1, X1$foo X2$foo ( - ). , X2$foo , . , , , , , JS .

+1

"" Closure Compiler . .

, http://closure-compiler.appspot.com/home

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @use_types_for_optimization true
// @formatting pretty_print
// @output_file_name default.js
// ==/ClosureCompiler==

/** @constructor */
function X(){}
X.prototype.foo = function() {alert("X")};

/** @constructor */
function Y(){}
Y.prototype.foo = function() {alert("Y")};

window.i = new X();
window.j = new Y();


/**
 * @param {!X} x
 */
window.keep = function(x) {
 x.foo();
}

* use_types_for_optimization * true false, , . , , keep X.

inlining.

, .

+1

The documentation says nothing about creating code that runs faster. The focus of the compiler has always been checks and code size. Although it can generate code that runs faster (usually by removing indirection), it can also create code that runs slower due to the creation of code that violates some optimization criteria for JS virtual machines (too much creation function, etc. )

0
source

Source: https://habr.com/ru/post/1525707/


All Articles