Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of !0 over boolean true [duplicate]

Tags:

javascript

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?
like image 731
Fizer Khan Avatar asked Aug 20 '14 12:08

Fizer Khan


1 Answers

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.

like image 90
Martin Tournoij Avatar answered Oct 01 '22 22:10

Martin Tournoij