int num = 0; while(true) { num++; if (num == 3) { System.out.println(3); } }

昨天看到一篇帖子,以下代码的运行结果是什么呢?

int num = 0;
while(true) {
    num++;
    if (num == 3) {
        System.out.println(3);
    }
}

答案是无数个3,因为i++超过int最大值会溢出,再从int最小值开始加

但是看到评论里以下代码的运行时间,我惊了,输出10000次用了53ms…

public class Main {
    public static void main(String[] args) {
        int num = 0, cnt = 0;
        long t = System.currentTimeMillis();
        while(cnt < 10000) {
            num++;
            if (num == 3) {
                System.out.println(3);
                cnt++;
            }
        }
        System.out.println(System.currentTimeMillis() - t);
    }
}

int最大值2147483647减去int最小值-2147483648是42亿多 4 ∗ 1 0 9 4 * 10^9 4109

这份代码要运行10000 * 4 ∗ 1 0 9 = 4 ∗ 1 0 13 4 * 10^9 = 4 * 10^{13} 4109=41013 数量级的语句,如果是普通计算机,要运行大概…几个小时?但是他只运行了53ms

查了一下天河一号的运行速度也就差不多这么快了,难道帖子里的人用的超算…

我用java11/16/20分别试了一下,发现每次输出都要间隔1秒多,怎么可能53ms这么快呢?难道他的编译器版本做了优化?

我看到他用的是jdk1.8,版本还没有我的新,心里想:怎么可能有优化…

但是我还是试了一下,

编译出来的.class文件是正常的,

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

public class Main {
    public Main() {
    }

    public static void main(String[] args) {
        int num = 0;
        int cnt = 0;
        long t = System.currentTimeMillis();

        while(cnt < 10000) {
            ++num;
            if (num == 3) {
                System.out.println(3);
                ++cnt;
            }
        }

        System.out.println(System.currentTimeMillis() - t);
    }
}

但是

输出瞬间刷屏,输出了一万次,竟然真的只有几十毫秒…

就算只执行10000次System.out.println(3);也得几十毫秒啊…

我又尝试了如下代码,循环里写三遍num++,运行时间又恢复正常了,一秒多输出一条。

int num = 0;
while(true) {
    num++;
    num++;
    num++;
    if (num == 3) {
        System.out.println(3);
    }
}

这是为什么呢…只有循环里有一遍num++的情况不正常…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小柳学渣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值