开发者社区> 问答> 正文

我写了两段代码,几乎完全一样,但是其中一个的运行速度比另一个(Java)快得多

我运行了这段代码:(外循环运行100次,内循环运行10亿次。)

long l = 0;

for(int i = 0; i < 100; i++) for(int j = 0; j < 1000000000; j++) l++;

System.out.println(l);

我跑了大约11到12秒。

然后,我运行了这段代码:

long l = 0; int i = 0, j = 0;

for(; i < 100; i++) for(; j < 1000000000; j++) l++;

System.out.println(l);

每当我运行它时,它就花费了大约100毫秒(0.1秒)。

有谁知道为什么会有很大的不同?我的理论是,对于每个'i'值,内部的for循环都必须再次初始化j,这使它可以执行更多操作,因此有意义的是它需要更长的时间。但是,差异是巨大的(大约100倍),并且在其他类似测试中,同一件事不会发生。

如果您想亲自观看,这是我的计时方式:

class Main { static long start, end; public static void main(String[] args) { start();

    long l = 0;
    int i = 0, j = 0;

    for(; i < 100; i++)
        for(; j < 1000000000; j++)
            l++;

    System.out.println(l);

    end();
    print();
}

public static void start() {
    start = System.currentTimeMillis();
}

public static void end() {
    end = System.currentTimeMillis();
}

public static void print() {
    System.out.println((end -  start) + " ms.");
}

}


问题来源:stackoverflow

展开
收起
七天一失眠 2020-04-11 15:50:33 1533 0
1 条回答
写回答
取消 提交回答
  • 做一个优秀的阿里云志愿者

    第二个函数仅在i的第一次迭代中通过j进行迭代。在这一点上,j超出了for循环的限制,并且不再运行,因为它不会在下一次迭代i时复位


    答案来源:stackoverflow

    2020-04-11 15:50:42
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载