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

编程入门 行业动态 更新时间:2024-10-25 05:18:22
本文介绍了Java for循环与while循环。性能差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 假设我有下面的代码,有三个for循环来做一些事情。如果我将最外层的循环更改为while循环,会运行得更快吗?谢谢~~

int length = 200; int test = 0; int [] input = new int [10]; (int i = 1; i <= length; i ++){ for(int j = 0; j <= length-i; j ++){ for(int k = 0; k 解决方案

不,改变循环的类型并不重要。

唯一能让速度更快的方法是减少循环嵌套,循环

循环与循环之间的唯一区别是 code> loop是定义它们的语法。没有任何性能差异。

int i = 0; while(i <20){ // do stuff i ++; $ / code $ / $ p $ b

相同:

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

(实际上,for循环更好一些,因为 i 将不在循环之后, i 将继续在而循环的情况下)。 循环仅仅是一个语法上更漂亮的循环方式。

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.

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.

更多推荐

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

本文发布于:2023-10-16 05:59:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1496695.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:差异   性能   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!