7

When i walk through minified file of javascript, i can see '!0' instead of boolean true and !1 instead of boolean false.

  • Is there any performance boost with it?
  • Do you recommend to use this notation in normal javascript code?
Fizer Khan
  • 88,237
  • 28
  • 143
  • 153

3 Answers3

6

It's shorter (ie. less bytes) ... Minification is typically done to save bandwidth, not for execution performance.

Consider a JS file to have 500 true and 500 false:

  • 2 bytes save for every true;
  • 3 bytes save for every false;
  • 2500 bytes saved for every request;
  • That's almost 10M saved for every 10,000 requests.

This may not sound like much, but if you're big (millions of requests) this (together with other minification techniques) can add up quite a bit... It's not just bandwidth that counts, a server can support only so many open tcp connections at a time, so if your request is done 10ms faster, then we can serve more people with the same capacity.

Edit: Florian Schöffl added a performance test; while there is some difference, it's only visible if we do hundreds of millions of tests, and even then it's very small. In other words: there is no measurable real-world performance difference, since the number of boolean tests even in large projects is much smaller (by several order of magnitude).

You should never type this in your JavaScript code manually; if you care about minification, use tools to do so. There are many good minification tools.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
1

There IS a difference in the performance. See here You can use this techniques if you want, but its worse for human eyes to read and only like 0.15% faster, so i dont recomend it!

Florian Schöffl
  • 499
  • 3
  • 12
  • But a = !1 is slower than a = false – Fizer Khan Aug 20 '14 at 13:00
  • 1
    @FizerKhan: Insignificantly slower, yes. Who cares about a few million operations per second more or less when it's running at `~800.000.000` ops / second? It's not like you'll see the difference, even if you have a thousand booleans. – Cerbrus Aug 20 '14 at 13:04
  • @FizerKhan: Surprisingly, `!1` is faster than `false` in some browsers - see Florian's jsperf link. (Though the difference is negligible.) – RichieHindle Aug 20 '14 at 13:05
0

Looks like !0 just a shortest equivalent of true.

Ivan Velichko
  • 6,348
  • 6
  • 44
  • 90