开发者

Closure Compiler - can a++ >= 3 become ++a > 3?

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 a开发者_运维技巧nd 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++ >=?


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:

a = 2e53
a++ >= 2e53 // true

a = 2e53
++a > 2e53 // false

Real question is what realized gain would such a very particular transformation have? :-0

Happy coding.


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:

  • it requires a lot of checking to ensure that the optimisation is safe,
  • it only applies in very specific circumstances that probably don’t come up very often, and
  • It only saves a single character, which hardly seems worth the bother.


Why not check all of the edge conditions yourself?

function b(a) {
    return a++ >= 3;
}

function b2(a) {
    return ++a > 3;
}

console.log(b(2) === b2(2))
console.log(b(3) === b2(3))
console.log(b(4) === b2(4))

The output is true in each case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜