【问题标题】:Why does Google Closure swap arguments?为什么 Google Closure 交换参数?
【发布时间】:2012-12-04 10:49:49
【问题描述】:

我已经看到 Google Closure 编译器在 if 子句中做了很多重写。例如:

if (a === 3) {…}

转向

if (3 === a) {…}

如果原语是第一个参数,JavaScript 中的比较是否更快,或者这是什么原因?

【问题讨论】:

  • Google 喜欢 Yoda :)
  • 你最好在这里问这个问题:groups.google.com/forum/?fromgroups#!forum/…
  • 如果有任何性能优势,可以忽略不计,至少在 Chrome 中:jsperf.com/yoda
  • 只是为了防止有人说这个(同样,已经有一个已删除的答案):它不是因为可能写=而不是==或@987654328 @。 Yoda-coding 是一些人做的事情(可悲),Closure 这样做的理由是零(因为那个原因),它已经知道= 不是偶然的。
  • Javascript minification of comparison statements 的可能副本;那里接受的答案是错误的。

标签: javascript google-closure


【解决方案1】:

来自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.
 *
 */

正如google closure compiler contributor 所述,代码 cmets 所指的压缩是指 gzip 压缩,而不是实际的缩小“压缩”。它可以提高 gzip 压缩的原因是,如果你的代码中有 0 === xx === 0,闭包编译器会将这两个规范化为 0 === x,这是重复的文本,因此可以更好地压缩。

那么还有:

typeof this.value == "object"

typeof this.key == "object"

唯一的字符串是:typeof this.valuekey== "object"

但如果你重新排序:

"object" == typeof this.value

"object" == typeof this.key

唯一的字符串是:"object" == typeof this.valuekey。较少的唯一字符串和相当长的重复字符串。

【讨论】:

  • 非常好,不错。人们可能希望获得更完整的描述(在评论中,而不是来自您),但至少那里有 something
  • +1。我喜欢说它扩展 AbstractPeepholeOptimization 的源代码部分:)
猜你喜欢
  • 2023-03-23
  • 2020-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
  • 2018-01-10
  • 2016-02-27
  • 1970-01-01
相关资源
最近更新 更多