最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

google closure compiler - Javascript minification of comparison statements - Stack Overflow

programmeradmin0浏览0评论

I was looking over one of the minified js files generated by closure. I found that wherever I'm checking for equality between a variable and string like,

a == "13" || a == "40"

closure replaces it with

"13" == a || "40" == a

Why is this modification done? Is there some performance advantage here?

I was looking over one of the minified js files generated by closure. I found that wherever I'm checking for equality between a variable and string like,

a == "13" || a == "40"

closure replaces it with

"13" == a || "40" == a

Why is this modification done? Is there some performance advantage here?

Share Improve this question asked Feb 13, 2012 at 6:51 Jophin JosephJophin Joseph 2,9534 gold badges30 silver badges41 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

This is done as for a minor gzip pression advantage. If you have "x == 1" and "1 == x" the piler switches it to "1 == x" in both cases and you get more regular code that presses better. The win is so minor, that I've considered deleting the code and saving the cpu cycles, but it is on for now. It has nothing to do with preventing programmer errors as it will never switch "x = 2" into "2 = x" as that would change the meaning of the program.

[UPDATE: See @John's answer, it makes more sense as to why a js minifier would do this, and should be the accepted answer]

As a general concept, this is to avoid programmer error. If you were modifying the code manually and put the variable first and constant second, it's possible to accidentally type:

a == '40' || a = '13'

Oops! We just set a to '13' instead of paring. By putting the constant on the left, we avoid this possibility:

'40' == a || '13' = a

Will throw an exception because you can't put a constant string on the left hand of an assignment operation.

So in some schools of thought, it's best practice to always put the constant on the left when doing equality parison against a constant. Looks like closure follows that practice.

These are called "yoda conditions".

Note that my personal preference is to actually to just put the constant on the right in most cases, because the code tends to read better, so I don't think the tradeoff is good enough. But I see the logic behind yoda conditions.

发布评论

评论列表(0)

  1. 暂无评论