Today I encountered a rather amazing behavior in java, or
is slower than and
!
I even made a test case that you can see at the below.Now I wonder why this happens?
Am I doing something wrong or does it happen just on my computer?
I don't see any reason that or
should be slower than and
specially with this significant difference. I want to test this phenomenon with some other languages, do you have any idea about this in general?
public class TestClass {
public static void main(String[] args) {
long[] or = new long[10];
long[] and = new long[10];
long lStartTime, lEndTime, difference = 0;
for (int idx = 0; idx < 10; idx++) {
lStartTime = System.nanoTime();
for (int i= 0; i < 1000000000; i++) {
int j = i | i+1 ;
}
lEndTime = System.nanoTime();
difference = lEndTime - lStartTime;
System.out.println("Elapsed milliseconds: " + difference/1000000);
or[idx] = difference;
lStartTime = System.nanoTime();
for (int i= 0; i < 1000000000; i++) {
int j = i & i+1 ;
}
lEndTime = System.nanoTime();
difference = lEndTime - lStartTime;
System.out.println("Elapsed milliseconds: " + difference/1000000);
and[idx] = difference;
System.out.println("------------------------------------" );
}
long tmp = 0;
for (long l : or) {
tmp += l;
}
tmp /= 10;
System.out.println("Elapsed milliseconds for or: " + tmp/1000000);
tmp = 0;
for (long l : and) {
tmp += l;
}
tmp /= 10;
System.out.println("Elapsed milliseconds for and: " + tmp/1000000);
}
}
results :
Elapsed milliseconds: 1600 Elapsed milliseconds: 1332 ------------------------------------ Elapsed milliseconds: 1609 Elapsed milliseconds: 1335 ------------------------------------ Elapsed milliseconds: 1609 Elapsed milliseconds: 1335 ------------------------------------ Elapsed milliseconds: 1542 Elapsed milliseconds: 1314 ------------------------------------ Elapsed milliseconds: 1705 Elapsed milliseconds: 1324 ------------------------------------ Elapsed milliseconds: 1559 Elapsed milliseconds: 1315 ------------------------------------ Elapsed milliseconds: 1526 Elapsed milliseconds: 1314 ------------------------------------ Elapsed milliseconds: 1568 Elapsed milliseconds: 1340 ------------------------------------ Elapsed milliseconds: 1551 Elapsed milliseconds: 1318 ------------------------------------ Elapsed milliseconds: 1574 Elapsed milliseconds: 1321 ------------------------------------ Elapsed milliseconds for or: 1584 Elapsed milliseconds for and: 1325