I'm trying to get the closure compiler to inline some of my code wrapped in configuration objects in SIMPLE mode without any type annotations. React does this and managed to bring down bundle sizes
I observed the following:
a.js
(function main() {
const config = {
log(m) {
console.log(m);
}
}
function reconciler(c) {
const log = c.log;
log('jere');
}
reconciler(config);
}())
when compiled returns
a.min.js
(function() {
(function(a) {
a = a.log;
a("jere");
})({
log: function(a) {
console.log(a);
}
});
})();
And,
b.js
(function main() {
const config = {
log(m) {
console.log(m);
}
}
function reconciler(c) {
const log = c.log;
c.log('here');
// log('jere');
}
reconciler(config);
}())
when compiled gives,
b.min.js
(function() {
console.log("here");
})();
On the other hand,
function main(){
const config = {
log: function log(m) {
console.log(m);
}
};
const log = config.log;
log('m');
log('m');
log('m');
log('m');
}
main()
gives
function main() {
console.log("m");
console.log("m");
console.log("m");
console.log("m");
}
main();
How does Closure Compiler inline? Is there is definite way to get it to inline wrapped functions?
Update: As suggested , I used --assume_function_wrapper
and it inlined the code better. But CC failed to inline if the function returns a value.
(function main() {
const config = {
log(m) {
console.log(m);
}
}
function reconciler(c) {
const log = c.log;
log('jere');
return {
foo() {
// More side effects
}
}
}
reconciler(config);
}())
There is no one answer. The compiler uses heuristics and side effect calculations to decide when to inline. The compiler is also less likely to inline in the global scope than in nested scopes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.