title: Why is Boolean() so slow in Javascript?
body: <p>According to the ECMAScript specification, both <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.9" rel="nofollow noreferrer">the unary logical NOT operator</a> (<code>!</code>) and <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.6.1" rel="nofollow noreferrer">the <code>Boolean()</code> function</a> use <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-9.2" rel="nofollow noreferrer">the internal function <code>ToBoolean()</code></a>, and the NOT operator also does a few checks to reverse the result.  So why is a double logical NOT operation <a href="http://jsperf.com/boolean-vs-double-negation" rel="nofollow noreferrer">much faster</a> than running the <code>Boolean()</code> function?</p>
  
  <p>I used the following piece of code to test which was faster:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function logicalNotOperator() {
    var start = performance.now();
    for (var i = 0; i &lt; 9999999; i++) !!Math.random();
    return 0.001 * (performance.now() - start);
  }
   
  function booleanFunc() {
    var start = performance.now();
    for (var i = 0; i &lt; 9999999; i++) Boolean(Math.random());
    return 0.001 * (performance.now() - start);
  }
  
  var logicalNotOperatorResult = logicalNotOperator();
  var booleanFuncResult = booleanFunc();
  var diff = booleanFuncResult - logicalNotOperatorResult;
  
  console.log('logicalNotOperator:', logicalNotOperatorResult);
  console.log('booleanFunc:', booleanFuncResult);
  console.log('diff:', diff);</code></pre>
  </div>
  </div>
  </p>
  
  <p><strong>Note:</strong> I am not referring to the <code>new Boolean()</code> constructor, but the <code>Boolean()</code> function that coerces the argument it's given to a boolean.</p>