8

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?

mritz_p
  • 3,008
  • 3
  • 28
  • 40
  • 8
    Google likes Yoda :) – Ja͢ck Dec 04 '12 at 10:50
  • You'd probably be better of asking that here: https://groups.google.com/forum/?fromgroups#!forum/closure-compiler-discuss – T.J. Crowder Dec 04 '12 at 10:57
  • 1
    If there is any performance benefit, it is negligible, at least in Chrome: http://jsperf.com/yoda – John Dvorak Dec 04 '12 at 11:03
  • Just to forestall someone saying this (again, there's already one deleted answer): It's **not** because of the possibility of writing `=` instead of `==` or `===`. Yoda-coding is something some humans do (sadly), there's zero reason for Closure to do it (for *that reason*), it already knows that there isn't an accidental `=`. – T.J. Crowder Dec 04 '12 at 11:43
  • 1
    possible duplicate of [Javascript minification of comparison statements](http://stackoverflow.com/questions/9256579/javascript-minification-of-comparison-statements); the accepted answer in there is wrong though. – Ja͢ck Dec 04 '12 at 11:53
  • @Jack thanks for that though, it never occurred to me that by compression in the code comments they mean gzip, not the minification process. Finally it makes sense – Esailija Dec 04 '12 at 14:42

1 Answers1

16

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.

Community
  • 1
  • 1
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Excellent, nice one. One could have wished for a fuller description (in the comment, not from you), but at least there's *something* there. – T.J. Crowder Dec 04 '12 at 11:40
  • 2
    +1. I love the part of the source code that says it extends `AbstractPeepholeOptimization` :) – Ja͢ck Dec 04 '12 at 12:23