today i was running some test to get a deeper understanding of which some instruction i have in my program, when i notice something unexpected. I run the following test to understand if it was slower using the BigDecimal pow method and then converting, or converting to double and using the Math.pow.
public static void main(String[] args){
BigDecimal myBd = new BigDecimal(2);
Date start = new Date();
System.out.println("inizio: " + start.toString());
for(int i=0; i++<10000000;){
Math.pow(myBd.doubleValue(),2);
}
Date t1 = new Date();
System.out.println("test 1 in:" +(t1.getTime() - start.getTime()));
for(int i=0; i++<10000000;){
myBd.pow(2);
}
Date t2 = new Date();
System.out.println("test 2 in:" +(t2.getTime() - t1.getTime()));
for(int i=0; i++<10000000;){
double wtf = Math.pow(myBd.doubleValue(),2);
}
Date t3 = new Date();
System.out.println("test 3 in:" +(t3.getTime() - t2.getTime()));
for(int i=0; i++<10000000;){
double wtf = myBd.pow(2).doubleValue();
}
Date t4 = new Date();
System.out.println("test 4 in:" +(t4.getTime() - t3.getTime()));
}
Here is a single output example:
test 1 in:1268 test 2 in:1358 test 3 in:1049 test 4 in:1308
Ok i found that it is better to convert and then using Math pow but... Wait, why the hell test1 is slower than test3 and in a similar way test 2 is slower than test4?
Running this more and more it is always the same. If i assign the returned value, it takes lesser then just calling the method.
Anyone does know the reason?