Java for loop vs. while loop. Performance difference?

前端 未结 16 1577
长发绾君心
长发绾君心 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:17

    It would only matter if you are using multi-thread or multiple processor programming. Then it would also depends on how you assign the loops to the various processors/threads.

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

    While Loop and For loop are same

    http://www.mkyong.com/java/while-loop-for-loop-and-iterator-performance-test-java/

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

    Someone suggested to test while vs for loops, so I created some code to test whether while loops or for loops were faster; on average, over 100,000 tests, while loop was faster ~95% of the time. I may have coded it incorrectly, I'm quite new to coding, also considering if I only ran 10,000 loops they ended up being quite even in run duration.

    edit I didn't shift all the array values when I went to test for more trials. Fixed it so that it's easier to change how many trials you run.

    import java.util.Arrays;
    
    class WhilevsForLoops {
    
     public static void main(String[] args) {
    
    final int trials = 100; //change number of trials
    final int trialsrun = trials - 1;
    
    boolean[] fscount = new boolean[trials]; //faster / slower boolean
    int p = 0; // while counter variable for for/while timers
    
    
    
    while (p <= trialsrun) {
         long[] forloop = new long[trials];
         long[] whileloop = new long[trials];
    
         long systimeaverage; 
         long systimenow = System.nanoTime();
         long systimethen = System.nanoTime();
    
         System.out.println("For loop time array : ");
         for (int counter=0;counter <= trialsrun; counter++) {
             systimenow = System.nanoTime();
             System.out.print(" #" + counter + " @");
             systimethen = System.nanoTime();
             systimeaverage = (systimethen - systimenow);
             System.out.print( systimeaverage + "ns |");
    
             forloop[counter] = systimeaverage; 
         }
    
         int count = 0;
         System.out.println(" ");
         System.out.println("While loop time array: ");
         while (count <= trialsrun) {
             systimenow = System.nanoTime();
             System.out.print(" #" + count + " @");
             systimethen = System.nanoTime();
             systimeaverage = (systimethen - systimenow);
             System.out.print( systimeaverage + "ns |");
    
             whileloop[count] = systimeaverage;
             count++;
         }
    
    
         System.out.println("===============================================");
         int sum = 0;
    
         for (int i = 0; i <= trialsrun; i++) {
            sum += forloop[i];
         }
    
         System.out.println("for loop time average: " + (sum / trials) + "ns");
    
         int sum1 = 0;
    
         for (int i = 0; i <= trialsrun; i++) {
             sum1 += whileloop[i];
         }
         System.out.println("while loop time average: " + (sum1 / trials) + "ns");
    
    
    
         int longer = 0;
         int shorter = 0;
         int gap = 0;
    
         sum = sum / trials;
         sum1 = sum1 / trials; 
    
         if (sum1 > sum) {
            longer = sum1;
            shorter = sum;
         }
         else {
            longer = sum;
            shorter = sum1;
         }
    
         String longa;
    
         if (sum1 > sum) {
            longa = "~while loop~";
         }
         else {
             longa = "~for loop~";
         }
    
         gap = longer - shorter; 
         System.out.println("The " + longa + " is the slower loop by: " + gap + "ns");
         if (sum1 > sum) {
         fscount[p] = true; }
         else {
             fscount[p] = false;
         }
         p++;
    }
    
        int forloopfc=0;
        int whileloopfc=0;
    
        System.out.println(Arrays.toString(fscount));
    
        for(int k=0; k <= trialsrun; k++) {
            if (fscount[k] == true) {
                forloopfc++; }
                else {
                    whileloopfc++;}
    
        }
    
        System.out.println("--------------------------------------------------");
    
        System.out.println("The FOR loop was faster: " + forloopfc + " times.");
        System.out.println("The WHILE loop was faster: " + whileloopfc + " times.");
     }
    
    }
    
    0 讨论(0)
  • 2020-11-28 10:20

    Even if the hypothesis of the while loop being faster than the for loop were true (and it's not), the loops you'd had to change/optimize wouldn't be the outer ones but the inner ones, because those are executed more times.

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

    you cant optimize it by changing it to while.

    you can just increment speed very very very very little by changing the line

    for (int k = 0; k < length - 1; k++) {
    

    by

    for (int k = 0; k < lengthMinusOne; k++) {
    

    where lengthMinusOne is calculated before

    this subtraction is just calculating almost (200x201/2) x (200-1) times and it is very little number for computer :)

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

    The difference between for and while is semantic :

    • In a while loop, you will loop as long as the condition is true, which can vary a lot, because you might, in your loop, modify variables using in evluating the while condition.
    • Usually, in a for loop, you loop N time. This N can be variable, but doesn't move until the end of your N loop, as usually developpers doesn't modify variables evaluated in the loop condition.

    It is a way to help other to understand your code. You are not obliged not to modify for loop variables, but it is a common (and good) practice.

    0 讨论(0)
提交回复
热议问题