Why is long slower than int in x64 Java?

前端 未结 8 891
野性不改
野性不改 2020-12-04 09:10

I\'m running Windows 8.1 x64 with Java 7 update 45 x64 (no 32 bit Java installed) on a Surface Pro 2 tablet.

The code below takes 1688ms when the type of i is a long

相关标签:
8条回答
  • 2020-12-04 09:40

    For the record, this version does a crude "warmup":

    public class LongSpeed {
    
        private static long i = Integer.MAX_VALUE;
        private static int j = Integer.MAX_VALUE;
    
        public static void main(String[] args) {
    
            for (int x = 0; x < 10; x++) {
                runLong();
                runWord();
            }
        }
    
        private static void runLong() {
            System.out.println("Starting the long loop");
            i = Integer.MAX_VALUE;
            long startTime = System.currentTimeMillis();
            while(!decrementAndCheckI()){
    
            }
            long endTime = System.currentTimeMillis();
    
            System.out.println("Finished the long loop in " + (endTime - startTime) + "ms");
        }
    
        private static void runWord() {
            System.out.println("Starting the word loop");
            j = Integer.MAX_VALUE;
            long startTime = System.currentTimeMillis();
            while(!decrementAndCheckJ()){
    
            }
            long endTime = System.currentTimeMillis();
    
            System.out.println("Finished the word loop in " + (endTime - startTime) + "ms");
        }
    
        private static boolean decrementAndCheckI() {
            return --i < 0;
        }
    
        private static boolean decrementAndCheckJ() {
            return --j < 0;
        }
    
    }
    

    The overall times improve about 30%, but the ratio between the two remains roughly the same.

    0 讨论(0)
  • 2020-12-04 09:40

    It's likely due to the JVM checking for safepoints when long is used (uncounted loop), and not doing it for int (counted loop).

    Some references: https://stackoverflow.com/a/62557768/14624235

    https://stackoverflow.com/a/58726530/14624235

    http://psy-lob-saw.blogspot.com/2016/02/wait-for-it-counteduncounted-loops.html

    0 讨论(0)
提交回复
热议问题