闭包编译器 - 可以++ >= 3 变为 ++a > 3?
我承认几天前我问过一个问题,为什么闭包编译器不缩短某些乍看起来可以缩短的代码,但这个原因在这种情况下不适用,我不太确定为什么它不被缩短这里。
我的代码是:
var a = 0;
function b() {
return a++ >= 3;
}
现在有前自增和后自增。区别在于返回值 - a++
返回 a
,然后然后递增它,++a
首先递增 a
和 then 返回它。
这归结为我的代码可以缩短为(忽略空白删除):
var a = 0;
function b() {
return ++a > 3;
}
但是,闭包编译器似乎并没有改变(或识别)这一点。
因此,我的问题是:使用 ++a >
代替 a++ >=
时会产生什么副作用?
I admit that I asked a question about why Closure Compiler does not shorten certain code which looks shortenable at first sight a few days ago already, but that reason is not applicable in this case and I'm not really sure why it isn't shortened here.
What code I have is:
var a = 0;
function b() {
return a++ >= 3;
}
Now there is pre-incrementing and post-incrementing. The difference is the return value - a++
returns a
and then increments it, ++a
first increments a
and then returns it.
What this comes down to is that my code could be shortened to (ignoring whitespace removal):
var a = 0;
function b() {
return ++a > 3;
}
However, Closure Compiler does not seem to alter (or recognise) this.
My question therefore is: what side effects could ++a >
have when used instead of a++ >=
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此构造有一个特定的边缘情况(但 3 除外)。
发生这种情况是因为 JavaScript 将数字存储为 IEEE-754 浮点 64 位双精度数,并且“仅”具有高达 2^53 的保证“精确”整数表示形式(尽管实现可能有更大的范围,但我不知道)。
这是在 Firefox 4 上的情况:
真正的问题是这样一个非常特殊的转变会带来什么实际收益? :-0
快乐编码。
There is a particular edge-case for this construct (but not for 3).
It occurs because JavaScript stores numbers as IEEE-754 float-point 64-bit doubles and "only" has a guaranteed "exact" integer-representation up to 2^53 (although implementations may have lee-way to have a higher range, I do not know).
This is on Firefox 4:
Real question is what realized gain would such a very particular transformation have? :-0
Happy coding.
如果右操作数(示例中的
3
)是 [-252 范围内的常量整数,则应用此大小优化是安全的,252]。在任何其他情况下(例如,如果右操作数是小数或非常大),它都是不安全的。我想 Closure 不会实现这种优化,因为:
It’s safe to apply this size-optimisation if the right-operand (
3
in your example) is a constant integer in the range [-252, 252]. In any other case (for example, if the right-operand is fractional or very large), it is not safe.I would imagine that Closure does not implement this optimisation because:
为什么不自己检查所有的边缘条件呢?
每种情况下的输出都是
true
。Why not check all of the edge conditions yourself?
The output is
true
in each case.