Java for loop vs. while loop. Performance difference?

前端 未结 16 1578
长发绾君心
长发绾君心 2020-11-28 09:35

Assume i have the following code, there are three for loop to do something. Would it run fast if i change the most outer for loop to while loop? thanks~~

<         


        
相关标签:
16条回答
  • 2020-11-28 10:35

    You can calculate it yourself.

    int length = 200;
    int test = 0;
    int[] input = new int[10];
    
    long startTime = new Date().getTime();
    
    for(int i = 1; i <= length; i++) {
        for (int j = 0; j <=length - i; j++) {
            for (int k = 0; k < length - 1; k++) {
                test = test + input[j + k];
            }
        }
    }
    
    long endTime = new Date().getTime();
    long difference = endTime - startTime;
    System.out.println("For - Elapsed time in milliseconds: " + difference);
    
    
    test = 0;
    input = new int[10];
    
    int i = 0, j = 0, k = 0;
    
    startTime = new Date().getTime();
    
    while(i < length) {
        while(j <= length - i ) {
            while(k < length - 1) {
                test = test + input[j + k];
                k++;
            }
            j++;
        }
        i++;
    }
    
    endTime = new Date().getTime();
    difference = endTime - startTime;
    System.out.println("While - Elapsed time in milliseconds: " + difference);
    
    0 讨论(0)
  • 2020-11-28 10:37

    There would be no performance difference. Try it out!

    The JVM and further, the compiler, would make both loops into something like

        label:
           ;code inside your for loop.
        LOOP label
    
    0 讨论(0)
  • 2020-11-28 10:39

    No, changing the type of loop wouldn't matter.

    The only thing that can make it faster would be to have less nesting of loops, and looping over less values.

    The only difference between a for loop and a while loop is the syntax for defining them. There is no performance difference at all.

    int i = 0;
    while (i < 20){
        // do stuff
        i++;
    }
    

    Is the same as:

    for (int i = 0; i < 20; i++){
        // do Stuff
    }
    

    (Actually the for-loop is a little better because the i will be out of scope after the loop while the i will stick around in the while loop case.)

    A for loop is just a syntactically prettier way of looping.

    0 讨论(0)
  • 2020-11-28 10:39

    This kind of micro-optimization is pointless.

    • A while-loop won’t be faster.
    • The loop structure is not your bottleneck.
    • Optimize your algorithm first.
    • Better yet, don’t optimize first. Only optimize after you have found out that you really have a bottleneck in your algorithm that is not I/O-dependant.
    0 讨论(0)
提交回复
热议问题