31

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~~

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];
        }
    }
}
4

17 回答 17

60

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.

于 2009-07-22T13:58:11.143 回答
32

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

  • while循环不会更快。
  • 循环结构不是你的瓶颈。
  • 首先优化你的算法。
  • 更好的是,不要先优化。只有在您发现您的算法确实存在不依赖于 I/O 的瓶颈之后才进行优化。
于 2009-07-22T14:13:30.330 回答
11

有人建议测试whilevsfor循环,所以我创建了一些代码来测试 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.");
 }

}
于 2012-11-26T07:50:21.207 回答
10

您无法通过将其更改为 while 来优化它。

您可以通过更改线路来增加速度非常非常非常少

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

经过

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

其中lengthMinusOne 是之前计算的

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

于 2009-07-22T14:05:58.653 回答
4

这是有关此事的文章的有用链接

根据它,While 和 For 几乎快两倍,但两者是相同的。

但是这篇文章写于 2009 年,所以我在我的机器上试了一下,结果如下:

  • 使用 java 1.7:Iterator 比 For 和 While 快大约 20%-30%(它们仍然相同)
  • 使用 java 1.6:迭代器比 For 和 While 快大约 5%(它们仍然相同)

所以我想最好的办法就是在你自己的版本和机器上计时,然后从中得出结论

于 2012-04-18T12:38:08.827 回答
2

即使 while 循环比 for 循环快的假设是正确的(事实并非如此),您必须更改/优化的循环也不会是外部循环,而是内部循环,因为这些循环执行的次数更多.

于 2009-07-22T14:17:05.707 回答
2

for 和 while 之间的区别是语义

  • 在 while 循环中,只要条件为真,您就会循环,这可能会有很大差异,因为您可能会在循环中修改用于评估 while 条件的变量。
  • 通常,在 for 循环中,您循环 N 次。这个 N 可以是可变的,但直到 N 循环结束时才会移动,因为通常开发人员不会修改循环条件中评估的变量。

这是一种帮助其他人理解您的代码的方法。您没有义务不修改 for 循环变量,但这是一种常见(且良好)的做法。

于 2009-07-22T14:29:16.560 回答
1

No, you're still looping the exact same number of times. Wouldn't matter at all.

于 2009-07-22T13:59:22.610 回答
1

看看你的算法!您是否事先知道数组中的哪些值被多次添加?

如果你知道你可以减少循环的数量,那会带来更好的性能。

于 2009-07-22T14:05:18.483 回答
1

不会有性能差异。试试看!

JVM 和编译器会将两个循环都变成类似的东西

    label:
       ;code inside your for loop.
    LOOP label
于 2011-12-16T18:53:48.727 回答
1

有没有人试过这样...

int i = 20;
while (--i > -1){
    // do stuff
}

相比:

for (int i = 0; i < 20; i++){
    // do Stuff
}
于 2016-07-07T09:34:32.330 回答
0

仅当您使用多线程或多处理器编程时才重要。然后它还取决于您如何将循环分配给各种处理器/线程。

于 2009-07-22T14:02:53.510 回答
0

While 循环和 For 循环是相同的

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

于 2016-07-22T10:20:06.207 回答
0

你可以自己计算。

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);
于 2020-11-20T18:07:42.617 回答
0

for循环和while循环都是迭代语句,但都有各自的特点。

句法

While 循环

//setup counter variable
int counter = 0;

while ( condition) {

    //instructions 

    //update counter variable
    counter++;  //--> counter = counter + 1;

}

循环

for (initialization; condition; iteration){
    //body of for loop
}

循环的for所有声明(初始化、条件、迭代)都在循环体的顶部。不利的是,在while循环中,只有初始化和条件位于循环体的顶部,并且迭代可以写在循环体的任何位置。

for 和 while 循环之间的主要区别

  1. for循环中,初始化、条件检查以及迭代变量的递增或递减仅在循环的语法中显式完成。相反,在While循环中,我们只能在循环的语法中初始化和检查条件。

  2. 当我们知道循环执行中必须发生的迭代次数时,我们使用 for 循环。另一方面,如果我们不知道循环中必须发生的迭代次数,那么我们使用while循环。

  3. 如果未能将条件语句放入for循环中,将导致循环的无限迭代。相反,如果您未能将条件语句放入while循环中,则会导致编译错误。

  4. 循环语法中的初始化语句for仅在循环开始时执行一次。相反,如果while循环在其语法中带有初始化语句,则每次循环迭代时都会执行while循环中的初始化语句。

  5. 循环中的迭代语句for将在循环体执行完之后执行。相反,迭代语句可以写在循环体中的任何地方,while所以在`while循环体中可能有一些语句在迭代语句执行之后执行。

于 2021-09-20T14:11:27.127 回答
0

不,这不会有很大的不同,唯一的事情是,如果您的嵌套循环可能需要考虑切换,例如出于组织目的,您可能希望在外部使用 while 循环并在其中包含 for 语句。这不会影响性能,但只会使您的代码看起来更干净/有条理

于 2020-05-08T03:56:56.443 回答
-2

基于此:https ://jsperf.com/loops-analyze (不是我创建的)while 循环通常比 for 循环慢 22%。至少在 Javascript 中是这样。

于 2017-07-21T16:07:10.893 回答