I did some investigation for Integer.bitCount recently. I found a interesting result that Integer.bitCount is much faster than my own func, even the code is the same.
I thought is due to JIT, but I checked the document, and found the JIT is based on runtime strategy. It confused me.
public static void main(String[] args) {
long sum = 0;
long start, end;
start = System.currentTimeMillis();
for (int i = Integer.MIN_VALUE; i != Integer.MAX_VALUE; i++) {
sum += bitCount(i);
//sum += Integer.bitCount(i);
}
end = System.currentTimeMillis();
System.out.println(sum);
System.out.println(end - start);
}
private static int bitCount(int i) {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
// for bitCount result
68719476736
8715
// for Integer.bitCount result
68719476736
1892