How can I get Google's Closure Compiler to eliminate attributes
When use the Google Closure Compiler advanced optimizations on the following code:
function add(v1, v2){
return {x: v1.x + v2.x, y: v1.y + v2.y};
}
function lengthSq(vec){
return vec.x*vec.x+vec.y*vec.y;
}
function test(v11, v12, v2开发者_开发知识库1, v22) {
return lengthSq(add({x:v11, y:v12},{x:v21, y:v22}));
}
window['func']=test;
I get this unsatisfying result:
window.func = function(b, c, a, d) {
b = {x:b, y:c};
a = {x:a, y:d};
a = {x:b.x + a.x, y:b.y + a.y};
return a.x * a.x + a.y * a.y
};
What I was hoping for:
window.func = function(a, b, c, d) {
return (a+c) * (a+c) + (b+d) * (b+d)
};
The real problem here is that I need to store values in attributes so that I can get multiple return values from functions. As far as I can tell, there is no other way to get multiple return values. I had initially hoped that the Closure Compiler would eliminate these for me, but it appears not.
Is it possible to have a functional or object oriented javascript library that can output code equivalent to the hand optimized example?
I am convinced my performance testing code is flawed, since the code without attributes is roughly 100 times faster on Chrome and Firefox, 12 times faster on Opera, and 4 times faster on IE9.
performance test of this code: http://jsperf.com/closure-compiler-vs-hand-optimized-vectors
There is a pending change to the compiler under review that attempts to do this: http://code.google.com/p/closure-compiler/issues/detail?id=394
精彩评论