Ran the following Java snippet which showed a big performance difference. Java 11.0.9.1 on Ubuntu 18.04.
With condition, like c = (res[i][j] >= 64)? 1 : 0;
, I got
time in ms: 1216
With no condition, like c = ((((res[i][j] - 64) & 0x80000000)>>31)+1);
I got
time in ms: 438
Questions:
- why is there such a big difference in performance
- Is
c = ((((res[i][j] - 64) & 0x80000000)>>31)+1);
the best option?
Thanks in advance.
public class FastCompare {
static final int ITEMS = 1000000;
static final int ATTRS = 1000;
public static void main(String args[]) {
byte[][] res = new byte[ITEMS][ATTRS];
int i;
int j;
for (i=0; i<ITEMS; i++) {
for (j=0; j<ATTRS; j++) {
res[i][j] = (byte)(i+j);
}
}
long start = System.currentTimeMillis();
long a = 1;
int c;
for (i = 0; i < ITEMS; i++) {
for (j=0; j<ATTRS; j++) {
c = (res[i][j] >= 64)? 1 : 0;
//c = ((((res[i][j] - 64) & 0x80000000)>>31)+1);
a += c;
}
}
System.out.println("time in ms: " + (System.currentTimeMillis() - start));
System.out.println("a="+a);
}
};