我怎样才能让谷歌的闭包编译器消除属性

发布于 2024-10-31 12:44:25 字数 1044 浏览 4 评论 0原文

当对以下代码使用 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 倍。

此代码的性能测试: http://jsperf.com/closure-compiler-vs -手工优化向量

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我为君王 2024-11-07 12:44:25

正在审查的编译器有一项待处理的更改,试图执行此操作: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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文