title: How exactly does V8 optimize/inline?
body: <p>I'm wondering whether it is possible to get knowledge of how exactly V8 optimizes and inlines things.</p>
  
  <p>I created three simple <a href="http://jsperf.com/optimizing-v8">test functions</a> which all calculate the sine of a angle in degrees. I put them all into closures so that V8 should be able to inline the local variables.</p>
  
  <hr>
  
  <p>1. Using a precalculated constant <code>Math.PI / 180</code>, and then do <code>Math.sin(x * constant)</code>.</p>
  
  <p>I used this code:</p>
  
  <pre><code>var test1 = (function() {
    var constant = Math.PI / 180; // only calculate the constant once
  
    return function(x) {
      return Math.sin(x * constant);
    };
  })();
  </code></pre>
  
  <hr>
  
  <p>2. Calculating the constant on the fly.</p>
  
  <pre><code>var test2 = (function() {
    var pi = Math.PI; // so that the compiler knows pi cannot change
                      // and it can inline it (Math.PI could change
                      // at any time, but pi cannot)
  
    return function(x) {
      return Math.sin(x * pi / 180);
    };
  })();
  </code></pre>
  
  <hr>
  
  <p>3. Using literal numbers and calculating the constant on the fly.</p>
  
  <pre><code>var test3 = (function() {
    return function(x) {
      return Math.sin(x * 3.141592653589793 / 180);
    };
  })();
  </code></pre>
  
  <hr>
  
  <p>Suprisingly, the results were as follows:</p>
  
  <pre><code>test1 - 25,090,305 ops/sec
  test2 - 16,919,787 ops/sec
  test3 - 16,919,787 ops/sec
  </code></pre>
  
  <p>It looks like <code>pi</code> did get inlined in <code>test2</code> as <code>test2</code> and <code>test3</code> result in exactly the same amount of operations per second.</p>
  
  <p>On the other hand, the division does not seem to be optimized (i.e. precalculated), since <code>test1</code> is significantly faster.</p>
  
  <ul>
  <li>Why is the constant not precalculated if you don't do so manually in this case?</li>
  <li>Is it possible to see how V8 exactly optimizes functions on a certain webpage?</li>
  </ul>