Does Java JIT cheat when running JDK code?

后端 未结 2 398
礼貌的吻别
礼貌的吻别 2020-12-04 04:49

I was benchmarking some code, and I could not get it to run as fast as with java.math.BigInteger, even when using the exact same algorithm. So I copied java.math.BigInteger

2条回答
  •  孤城傲影
    2020-12-04 05:15

    In Java 8 this is indeed an intrinsic method; a slightly modified version of the method:

     private static BigInteger test() {
    
        Random r = new Random(1);
        BigInteger c = null;
        for (int i = 0; i < 400000; i++) {
            int s1 = 400, s2 = 400;
            BigInteger a = new BigInteger(s1 * 8, r), b = new BigInteger(s2 * 8, r);
            c = a.multiply(b);
        }
        return c;
    }
    

    Running this with:

     java -XX:+UnlockDiagnosticVMOptions  
          -XX:+PrintInlining 
          -XX:+PrintIntrinsics 
          -XX:CICompilerCount=2 
          -XX:+PrintCompilation   
           
    

    This will print lots of lines and one of them will be:

     java.math.BigInteger::multiplyToLen (216 bytes)   (intrinsic)
    

    In Java 9 on the other hand that method seems to not be an intrinsic anymore, but in turn it calls a method that is an intrinsic:

     @HotSpotIntrinsicCandidate
     private static int[] implMultiplyToLen
    

    So running the same code under Java 9 (with the same parameters) will reveal:

    java.math.BigInteger::implMultiplyToLen (216 bytes)   (intrinsic)
    

    Underneath it's the same code for the method - just a slightly different naming.

提交回复
热议问题