Javascript minification of comparison statements

对着背影说爱祢 提交于 2019-11-28 08:29:02

问题


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?


回答1:


[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 comparing. 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 comparison 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.




回答2:


This is done as for a minor gzip compression advantage. If you have "x == 1" and "1 == x" the compiler switches it to "1 == x" in both cases and you get more regular code that compresses 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.



来源:https://stackoverflow.com/questions/9256579/javascript-minification-of-comparison-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!