Why is 2 * (i * i) faster than 2 * i * i in Java?

前端 未结 10 711
一生所求
一生所求 2020-12-22 14:43

The following Java program takes on average between 0.50 secs and 0.55 secs to run:

public static void main(String[] args) {
    long startTime = System.nano         


        
10条回答
  •  执笔经年
    2020-12-22 15:01

    More of an addendum. I did repro the experiment using the latest Java 8 JVM from IBM:

    java version "1.8.0_191"
    Java(TM) 2 Runtime Environment, Standard Edition (IBM build 1.8.0_191-b12 26_Oct_2018_18_45 Mac OS X x64(SR5 FP25))
    Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)
    

    And this shows very similar results:

    0.374653912 s
    n = 119860736
    0.447778698 s
    n = 119860736
    

    (second results using 2 * i * i).

    Interestingly enough, when running on the same machine, but using Oracle Java:

    Java version "1.8.0_181"
    Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
    Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
    

    results are on average a bit slower:

    0.414331815 s
    n = 119860736
    0.491430656 s
    n = 119860736
    

    Long story short: even the minor version number of HotSpot matter here, as subtle differences within the JIT implementation can have notable effects.

提交回复
热议问题