Why does Google Closure swap arguments?

吃可爱长大的小学妹 提交于 2019-11-30 04:22:25

问题


I've seen the Google Closure compiler do a lot of rewriting in if-clauses. For example:

if (a === 3) {…}

turns to

if (3 === a) {…}

Are comparisons faster in JavaScript, if the primitive is the first argument, or what is the reason for this?


回答1:


From ReorderConstantExpression.java:

/**
 * Reorder constant expression hoping for a better compression.
 * ex. x === 0 -> 0 === x
 * After reordering, expressions like 0 === x and 0 === y may have higher
 * compression together than their original counterparts.
 *
 */

As stated by a google closure compiler contributor, the compression the code comments are referring to means gzip compression, not the actual minification "compression". The reason it can improve gzip compression is that if you have 0 === x and x === 0 in your code, the closure compiler normalizes both of these to 0 === x, which is duplicated text and thus compresses better.

Then there is also:

typeof this.value == "object"

typeof this.key == "object"

The unique strings are: typeof this., value, key and == "object"

But if you reorder:

"object" == typeof this.value

"object" == typeof this.key

The unique strings are: "object" == typeof this., value and key. Less unique strings and quite a long duplicate one.



来源:https://stackoverflow.com/questions/13701205/why-does-google-closure-swap-arguments

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