I tried to check if it works var & 3faster than var % 4in java (it can also be 2 ^ n - 1 against% 2 ^ n). I made a simple program to calculate the average time needed to perform the calculations, but I get strange results, and I can not conclude. For about 1000 calculations, the average value mod 4takes much longer, but when I try to do about 1,000,000 calculations, both average values are about the same ... I suspect this is due to java optimization of my code, but I'm not sure.
Which of these two operations should be faster and how is it implemented %?
Thank!
EDIT: Here is my test program.
long startTime, time, sum;
int iterations = 1000;
int v;
sum = 0;
for(int i = 0; i < iterations; i++)
{
startTime = System.nanoTime();
v = i % 4;
time = System.nanoTime();
sum += time-startTime;
}
System.out.println("Mod 4 : "+(sum/iterations));
sum = 0;
for(int i = 0; i < iterations; i++)
{
startTime = System.nanoTime();
v = i & 3;
time = System.nanoTime();
sum += time-startTime;
}
System.out.println("& 3 : "+(sum/iterations));
100 130 mod 4 25060 & 3.
1000 1792 mod 4 81 & 3.
1000000 50 , mod 4 .