Java for 循环与 while 循环.性能差异? [英] Java for loop vs. while loop. Performance difference?

查看:45
本文介绍了Java for 循环与 while 循环.性能差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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.

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

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++;
}

等同于:

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

(实际上 for 循环要好一点,因为 i 将在循环后超出范围,而 i 将留在 while 循环案例.)

(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.)

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

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

这篇关于Java for 循环与 while 循环.性能差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆