Is it possible to make Google Closure compiler *not* inline certain functions?

一曲冷凌霜 提交于 2020-01-22 12:33:03

问题


Closure compiler is inlining a function, but the code size is smaller if that function is not inlined (I only care about code size - this is for JS1k). Can I tell the compiler that I don't want that function inlined?

Edit: Just to explain a bit better, here's my function:

function lineTo(x,y) {
  a.lineTo(x,y);
}

where a in the canvas context. Because there are so many a.lineTos in the code, having this function used is worth it. Like this, my code is 1019 bytes (and all the lineTos are replaced by a.lineTo). If I change the function to:

function lineTo(x,y) {
  a.lineTo(x,y);
  console.log();
}

the new line somehow forces the compiler to not inline this function, which gives me 993 bytes. So if I could get rid of the console.log(); I'd save another 14 bytes.


回答1:


From the tutorial:

If...you find that Closure Compiler is removing functions you want to keep, there are two ways to prevent this:
* Move your function calls into the code processed by Closure Compiler.
* Export the symbols you want to keep.

You probably want the second, which is discussed here, but basically comes down to explicitly setting it as a window property:

function foo() {
}
window['foo'] = foo;

For your JS1k submission, you'd just leave the last line off as it's unneeded. note that Closure will still rename the function, but as it starts renaming your symbols with the name a and continues from there, it's unlikely to make your names longer overall.

You can try it out with the online compiler service. If you paste this in:

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// ==/ClosureCompiler==

// ADD YOUR CODE HERE
function hello(name) {
  alert('Hello, ' + name);
}
hello('New user');

...the compiled result is

alert("Hello, New user");

But if you add

window['hello'] = hello;

...to the end, the compiled result is:

function a(b){alert("Hello, "+b)}a("New user");window.hello=a;


来源:https://stackoverflow.com/questions/4297685/is-it-possible-to-make-google-closure-compiler-not-inline-certain-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!