本文介绍了嵌套循环的效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅以下代码段:

    Long first_begin = System.currentTimeMillis();

    // first nested loops
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 1000000; j++) {
            // do some stuff
        }
    }
    System.out.println(System.currentTimeMillis() - first_begin);
    // second nested loops
    Long seconde_begin = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
        for (int j = 0; j < 10; j++) {
            // do some stuff
        }
    }
    System.out.println(System.currentTimeMillis() - seconde_begin);

我想知道为什么第一个嵌套循环的运行速度比第二个慢?

I am wondering why the first nested loops is running slower than the second one?

致谢!

重要提示!:很抱歉,当我第一次提出此问题时,我无意中使变量j以1开头,我已进行了更正.

Important Note!: I am sorry that I made the variable j beginning with 1 accidentally when this question is first asked, I have made the correction.

更新:循环中没有任何特定的逻辑,我只是​​在做一些测试,实际上这是在面试中提出的一个问题,面试官提示我更改循环的顺序以实现更好的性能.顺便说一句,我正在使用JDK1.5.经过一番测试之后,我现在更加困惑了,因为程序的结果不一致-有时第一个循环的运行速度比第二个循环快,但是大多数时候它的运行速度比第二个循环慢.

Update:there is not any specific logic within the loops, I am just doing some test, actually this is a question asked during an interview and the interviewer hint me to change the order of loops to achieve better performance. BTW, I am using JDK1.5. after some test I am more confused now, because the result of program is not consistent---sometime the first loop running faster than the second one, but most of the time it's running slower than second one.

推荐答案

此答案用于更新的问题:

This answer is for the updated question:

  • 如果要访问二维数组,例如int[][],则在内部循环中具有较大值的二维数组应该更慢.数量不多,但仍然如此.要对问题有所了解,请在Joel的一篇博客文章中阅读有关街头画家Shlemiel 的信息.
  • 获得不一致结果的原因是您没有执行任何JVM预热. JVM会不断分析运行的字节码并对其进行优化,通常只有经过30到50次迭代后,JVM才能以最佳速度运行.是的,这意味着您需要先运行该代码数十次,然后再运行两次平均基准测试,因为Garbage Collector会降低运行速度.
  • 一般注意,使用Long对象而不是long原语只是愚蠢的,JVM最有可能通过将其替换为原语(如果可以,如果不能,则替换原语)来对其进行优化,必然会有一些(,尽管使用起来非常慢).
  • If you're accessing two dimensional array such as int[][], the one with the larger value in the inner loop should be slower. Not by much but still. To somewhat understand the problem, read about Shlemiel the street painter in one of Joel's blog posts.
  • The reason you're getting inconsistent results is that you're not performing any JVM warmup. JVM constantly analyzes the bytecode that is run and optimizes it, usually only after 30 to 50 iterations it runs at optimal speed. Yes, this means you need to run the code first a couple of dozen times and then benchmark it from an average of another couple dozen runs because of Garbage Collector which will slow couple of runs.
  • General note, using Long object instead of long primitive is just dumb, JVM most likely optimizes it by replacing it with the primitive one if it can and if it can't, there's bound to be some (albeit extremely minor) constant slowdown from using it.

这篇关于嵌套循环的效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:23