Java中有趣的行为

时间:2018-09-13 07:22:42

标签: java

我运行此代码并获取两个循环块的运行时间。有趣的是,当我为j 2设置上限时,每个块的运行时间约为3500ms,但当我为j 10上限运行时,运行时间为<10ms。 快速代码:

        long start = System.currentTimeMillis();
        int a = 10;
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            for (int j = 0; j < 10; j++) {
                for (int k = 0; k < 1; k++) {
                    a += 2;
                }
            }
        }
        long finish = System.currentTimeMillis();
        System.out.println(finish - start);

        start = System.currentTimeMillis();
        a = 10;
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            for (int j = 0; j < 10; j++) {
                for (int k = 0; k < 1; k++) {
                    a = a + 2;
                }
            }
        }
        finish = System.currentTimeMillis();
        System.out.println(finish - start);

慢速代码:

        long start = System.currentTimeMillis();
        int a = 10;
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            for (int j = 0; j < 2; j++) {
                for (int k = 0; k < 1; k++) {
                    a += 2;
                }
            }
        }
        long finish = System.currentTimeMillis();
        System.out.println(finish - start);

        start = System.currentTimeMillis();
        a = 10;
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            for (int j = 0; j < 2; j++) {
                for (int k = 0; k < 1; k++) {
                    a = a + 2;
                }
            }
        }
        finish = System.currentTimeMillis();
        System.out.println(finish - start);

为什么10的运行速度比2快?!

0 个答案:

没有答案