title: Why is 2 * (i * i) faster than 2 * i * i in Java?
body: <p>The following Java program takes on average between 0.50 secs and 0.55 secs to run:</p>
  <pre class="lang-java prettyprint-override"><code>public static void main(String[] args) {
      long startTime = System.nanoTime();
      int n = 0;
      for (int i = 0; i &lt; 1000000000; i++) {
          n += 2 * (i * i);
      }
      System.out.println(
          (double) (System.nanoTime() - startTime) / 1000000000 + &quot; s&quot;);
      System.out.println(&quot;n = &quot; + n);
  }
  </code></pre>
  <p>If I replace <code>2 * (i * i)</code> with <code>2 * i * i</code>, it takes between 0.60 and 0.65 secs to run. How come?</p>
  <p>I ran each version of the program 15 times, alternating between the two. Here are the results:</p>
  <pre class="lang-text prettyprint-override"><code> 2*(i*i)  │  2*i*i
  ──────────┼──────────
  0.5183738 │ 0.6246434
  0.5298337 │ 0.6049722
  0.5308647 │ 0.6603363
  0.5133458 │ 0.6243328
  0.5003011 │ 0.6541802
  0.5366181 │ 0.6312638
  0.515149  │ 0.6241105
  0.5237389 │ 0.627815
  0.5249942 │ 0.6114252
  0.5641624 │ 0.6781033
  0.538412  │ 0.6393969
  0.5466744 │ 0.6608845
  0.531159  │ 0.6201077
  0.5048032 │ 0.6511559
  0.5232789 │ 0.6544526
  </code></pre>
  <p>The fastest run of <code>2 * i * i</code> took longer than the slowest run of <code>2 * (i * i)</code>. If they had the same efficiency, the probability of this happening would be less than <code>1/2^15 * 100% = 0.00305%</code>.</p>