Java的for循环和while循环。性能差异?

34

假设我有以下代码,其中有三个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];
        }
    }
}

1
由于数组未被填充,它将进行优化以使 test = 0; 因此 test = test + input[j + k]; 将始终为零。 - Kelly S. French
1
计时!虽然我不懂Java,但我知道在Perl中,C风格的for循环比while循环慢,特别是在读取文件的情况下。 - xenoterracide
15个回答

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` 循环体中,可以有一些语句在迭代语句执行后执行。


0

只有在使用多线程或多处理器编程时才会有影响。这也取决于您如何将循环分配给各个处理器/线程。


0
不,这不会带来很大的差别,唯一需要考虑的是如果你嵌套循环,可能出于组织目的,你可以在外部使用while循环并在其中添加for语句。这不会影响性能,只是使你的代码更加清晰和有组织。

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);

-2
根据这个链接:https://jsperf.com/loops-analyze(不是我创建的),一般情况下while循环比for循环慢22%。至少在Javascript中是这样的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接