I was wondering how the power in Java and the performance of the available methods are calculated. So I wrote a simple test to test the operations of Math.pow() , * and ^ .
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 < 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 < 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 < SIZE; i++) { arr1[i] = i^4; } end3 = System.currentTimeMillis(); System.out.println(" ^: " + (end3 - st3));
and if the first two results were expected:
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
the third is a bit confusing. Why is ^ always a little faster than simple multiplication, and which one should I use?
All tests were performed with JRE 1.7 under similar conditions.
source share