title: Multiplication vs ^ operator vs Math.pow() for integer powers
body: <p>I got curious about the way power calculation is done in Java and the performance of available methods. So I wrote a simple test to check on <code>Math.pow()</code>, <code>*</code> and <code>^</code> operations.</p>
  
  <pre><code>public static void main(String[] args) {
  
      int SIZE = 100000000;
  
      int[] arr1 = new int[SIZE];
      long st1, end1, st2, end2, st3, end3;
  
      st1 = System.currentTimeMillis();
      for (int i = 0; i &lt; SIZE; i++) {
          arr1[i] = (int) Math.pow(i, 4);
      }
      end1 = System.currentTimeMillis();
      System.out.println("pow: " + (end1 - st1));
  
      arr1 = new int[SIZE];
      st2 = System.currentTimeMillis();
      for (int i = 0; i &lt; SIZE; i++) {
          arr1[i] = i * i * i * i;
      }
      end2 = System.currentTimeMillis();
      System.out.println("mul: " + (end2 - st2));
  
      arr1 = new int[SIZE];
      st3 = System.currentTimeMillis();
      for (int i = 0; i &lt; SIZE; i++) {
          arr1[i] = i^4;
      }
      end3 = System.currentTimeMillis();
      System.out.println("  ^: " + (end3 - st3));
  
      //to prevent optimizations form skipping the calculations
      for (int i = 0; i &lt; SIZE; i++) {
          if (arr1[i] == 1){
              System.out.println(1);
          }
      }
      System.out.println("done");
  }
  </code></pre>
  
  <p>and if the first two results were quite expected:</p>
  
  <pre><code>pow: 19253 19128 19205 19145 19185 19130 19162 19177 19191 19157 | 19173
  mul: 91 86 91 85 98 90 90 105 87 95 | 92
    ^: 80 85 80 70 60 65 75 60 70 60  | 71
  </code></pre>
  
  <p>the third one is a bit confusing. How come <code>^</code> is always a bit faster than simple multiplication and which one should be used?</p>
  
  <p>All the tests were run with JRE 1.7 in similar conditions.</p>