java的while与c,for循环VS while循环在编程语言,c ++ / java?

Which is better for performance? This may not be consistent with other programming languages, so if they are different, or if you can answer my question with your knowledge in a particular language, please explain.

I will be using c++ as an example, but I would like to know how it works in java, c, or any other mainstream languages.

int x = 0;

while (x < 10) {

cout << x << "\n ";

x++;

}

VS

for ( int x = 1; x < 10; x++)

cout << x << "\n ";

Which one performs better? If it is the for loop, then lets say that there was an integer already declared that we could use in the while loop increment, that we didn't need to create just for the while loop?

example:

int age = 17; //this was made for something else in the code, not a while loop. But fortunately for us, our while loop just so happened to need the number 17.

while (age < 25) {

cout << age << "\n ";

age++;

}

Would this instance make the while loop a better choice than creating a for loop? And I have seen questions somewhat similar to this, but I do not believe that this is a duplicate, or any of the answers on those other questions answered my question.

I want an explanation on this question, explaining if it is compiler specific, how it works, or whatever is a good answer to this question.

解决方案

I find it hard to imagine situations where the code samples you give would have different performance characteristics.

I do have a mild curiosity for you though. In Pascal like languages (e.g. Delphi) the loop limits are evaluated only once. This differs from the C like languages where the loop limits are evaluated each iteration. This can have performance implications but of course its trivial to write performant code in C like languages by introducing a local outside the loop.

For example:

Delphi

for i := 0 to List.Count-1 do

DoStuff(List[i]);

List.Count is only evaluated once.

C++

for (int i=0; i

DoStuff(List.getItem(i));

Here, List.getCount() is called every time around the loop.

If it transpires that evaluating the loop limits is expensive then this difference can be relevant. Naturally it is trivial to evaluate List.getCount() outside the loop and store the result in a local variable.

Having compared the for loops of Pascal and C/C++ I would say that the Pascal version is very simplistic in comparison. This is not necessarily a bad thing because for more complex there is always while available.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值