Javascript缩小比较语句 [英] Javascript minification of comparison statements
问题描述
我正在查看由闭包生成的一个缩小的js文件。我发现无论我在哪里检查变量和字符串之间是否相等,
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"
闭包替换为
"13" == a || "40" == a
为什么要进行此修改?这里有一些性能优势吗?
Why is this modification done? Is there some performance advantage here?
推荐答案
[更新:请参阅@ John的回答,这对于为什么更有意义一个js minifier会这样做,应该是接受的答案]
作为一般概念,这是为了避免程序员错误。如果您手动修改代码并将变量放在第一位且常数为第二位,则可能会意外输入:
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'
哎呀!我们只需将 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.
这些被称为yoda条件。
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.
这篇关于Javascript缩小比较语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!