Java for循环与while循环.性能差异?

29 java for-loop while-loop

假设我有以下代码,有三个for循环来做某事.如果我将最外部的for循环更改为while循环,它会快速运行吗?谢谢~~

int length = 200;
int test = 0;
int[] input = new int[10];

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];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

jjn*_*guy 55

不,改变循环的类型无关紧要.

唯一能使它更快的事情就是减少循环嵌套,并循环使用较少的值.

for循环和while循环之间的唯一区别是定义它们的语法.根本没有性能差异.

int i = 0;
while (i < 20){
    // do stuff
    i++;
}
Run Code Online (Sandbox Code Playgroud)

是相同的:

for (int i = 0; i < 20; i++){
    // do Stuff
}
Run Code Online (Sandbox Code Playgroud)

(实际上for循环更好一点,因为i循环后它将超出范围,而循环情况下i会停留在范围内while.)

for循环只是一种语法更漂亮的循环方式.

  • 你可以在i周围添加范围,一旦你完成它就把它从堆栈中剔除:D (5认同)
  • 由于 continue 的行为方式,for 循环和 while 循环实际上略有不同。增量将始终发生在 for 循环中,而 while 循环中的 continue 将跳过它,导致循环永远继续。 (2认同)

Bom*_*mbe 30

这种微优化是没有意义的.

  • while循环不会更快.
  • 循环结构不是你的瓶颈.
  • 首先优化算法.
  • 更好的是,不要先优化.只有在发现您的算法确实存在不依赖于I/O的瓶颈之后才进行优化.


ufu*_*gun 9

你不能通过改变它来优化它.

你可以通过改变线来非常非常非常地增加速度

for (int k = 0; k < length - 1; k++) {
Run Code Online (Sandbox Code Playgroud)

通过

for (int k = 0; k < lengthMinusOne; k++) {
Run Code Online (Sandbox Code Playgroud)

其中lengthMinusOne之前计算过

这个减法只是计算几乎(200x201/2)x(200-1)次,这对于计算机来说是非常少的数字:)

  • Java编译器通常会优化这些调用.但是你在技术上是正确的,因为它更快. (6认同)
  • 嘿,我有一半期待有人建议将`k ++'改为`++ k`:D (4认同)

Sle*_*epy 9

有人建议测试whilevs for循环,所以我创建了一些代码来测试while循环或for循环是否更快; 平均而言,超过100,000次测试,while循环更快〜95%的时间.我可能编码不正确,我对编码很新,还考虑到我是否只运行了10,000个循环,它们最终在运行持续时间内非常均匀.

编辑当我去测试更多试验时,我没有移动所有数组值.修正了它,以便更改您运行的试验次数.

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.");
 }

}
Run Code Online (Sandbox Code Playgroud)