3

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
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
kidd
  • 33
  • 2

1 Answers1

6

Your benchmark is not accurate. But disregarding that, one reason is because Integer#bitCount is marked as @HotSpotIntrinsicCandidate. This means that the HotSpot JVM can replace the method body with assembly code to improve performance. From the annotation's source code:

The @HotSpotIntrinsicCandidate annotation is specific to the HotSpot Virtual Machine. It indicates that an annotated method may be (but is not guaranteed to be) intrinsified by the HotSpot VM. A method is intrinsified if the HotSpot VM replaces the annotated method with hand-written assembly and/or hand-written compiler IR -- a compiler intrinsic -- to improve performance. The @HotSpotIntrinsicCandidate annotation is internal to the Java libraries and is therefore not supposed to have any relevance for application code.

Try disabling intrinsics and running your test again; you should see a significant slowdown.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
  • [`-XX:DisableIntrinsic=_bitCount_i`](https://gist.github.com/apangin/7a9b7062a4bd0cd41fcc#file-hotspot-jvm-intrinsics) – Sotirios Delimanolis Apr 30 '19 at 04:22
  • 1
    Thanks very much. I tried that option. It did show the main reason is intrinsic. But I didn't find out that @HotSpotIntrinsicCandidate annotation in source code. Only found a func list in http://hg.openjdk.java.net/jdk8/jdk8/hotspot/file/87ee5ee27509/src/share/vm/classfile/vmSymbols.hpp#l581 – kidd Apr 30 '19 at 06:11