我怎样才能让谷歌的闭包编译器消除属性
当对以下代码使用 Google Closure Compiler 高级优化时:
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, v21, v22) {
return lengthSq(add({x:v11, y:v12},{x:v21, y:v22}));
}
window['func']=test;
我得到了这个令人不满意的结果:
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
};
我所希望的:
window.func = function(a, b, c, d) {
return (a+c) * (a+c) + (b+d) * (b+d)
};
这里真正的问题是我需要将值存储在属性中,以便我可以从函数中获取多个返回值。据我所知,没有其他方法可以获取多个返回值。我最初希望闭包编译器会为我消除这些,但似乎没有。
是否有可能有一个函数式或面向对象的 JavaScript 库,可以输出与手动优化示例等效的代码?
我确信我的性能测试代码有缺陷,因为没有属性的代码大约快 100 倍在 Chrome 和 Firefox 上,在 Opera 上快 12 倍,在 IE9 上快 4 倍。
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, v21, 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正在审查的编译器有一项待处理的更改,试图执行此操作:http://code.google.com/p/closure-compiler/issues/detail?id=394
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