I wanted to open up this discussion to those interested. I was running some tests of my own and found there was no difference between Math.abs() and ((a ^ (a >> 31)) - (a >> 31)). I just want to make sure that I am conducting these tests correctly.
First my machine specs:
HP Compaq P4 2.66GHz
768MB
EDIT: JDK = 1.5.0_05-b05
Here is the class that I set up:
public final class MathTest {
public static int abs(int a) {
return ((a ^ (a >> 31)) - (a >> 31));
}
}
When I run with this test code:
public class Test {
public static void main(String args[]) {
int a = -2;
int b;
long time1;
long time2;
time1 = System.nanoTime();
b = MathTest.abs(a);
time2 = System.nanoTime();
System.out.println((time2 - time1));
}
}
The times are:
MathTest.abs() = 1084774 nano seconds
Math.abs() = 41346 nano seconds
but when I change the test code to this:
public class Test {
public static void main(String args[]) {
int a = -2;
int b;
long time1;
long time2;
for(int i=0;i<1000000;i++) {
b = Math.abs(a);
}
time1 = System.nanoTime();
for(int i=0;i<100000;i++) {
b = Math.abs(a);
}
time2 = System.nanoTime();
System.out.println((((double)time2 - (double)time1) / 100000.0));
}
}
The times are:
MathTest.abs() = 2.34 nano seconds
Math.abs() = 2.34 nano seconds
So when I do a warm up loop and then average 100,000 calls, there is no difference. Am I running this test correctly?
