As we know, JIT will optimize division to have a better performance. But when I try to calculate time that division and right shift cost:
long j=0;
long a1=Calendar.getInstance().getTimeInMillis();
for (long i = 0; i < 999999999l; i++) {
j=i/2;//or j=i>>1;
}
long a2=Calendar.getInstance().getTimeInMillis();
System.out.println(a2-a1);
Result: j=i/2; 1070ms j=i>>1; 702ms
I try it on different platforms but the results are quite same: right shift performs better. Why doesn't JVM or JIT turn the /2 into >>1 to get better performance?
Thanks all. It seems that if dividend is a variable, compiler will not do the optimization. I change the dividend into a constant and the result shows /2 and >>1 perform equivalent. PS. Thanks, System.currentTimeMillis() is better.