You may have confused with the topic. So let me explain it.

In most of the computing languages , we have for and while loop. But in my example , I will declare the loop in c#.

When you decalre a for loop and while loop like this.

1.For loop

 for(i=0;i<10;i++)
   {
     //do something
   }

2.While loop

 int i=0;
 while(i<10)
   {
     //do something
     i++;
   }

From the 2 loops. When it comes to the complier , do they complie the same things?(except the int i that was declared outside the while loop.) If they don't , which one is better or more efficient?

Thanks in advance

有帮助吗?

解决方案

The simple answer to your question is "yes, they will compile to the same code." Sometimes. It's going to depend on the language and on the compiler. As far as C# is concerned, any difference in the generated code will be so small as to be irrelevant in terms of running time.

Any for loop can be re-coded as a while, and vice-versa. For example, this while loop:

bool done = false;
while (!done)
{
    // do stuff
}

Can be re-coded as a for:

for (bool done = false; !done;)
{
    // do stuff
}

for and while are just abstractions. Sometimes it's easier for us to think of stepping through a list, which is the basis (although certainly not the only use) of the for statement. Other times we want to do something while some condition remains true--thus we use while. And some languages have an until (or, in C, the do ... while), which puts the condition at the end.

These are all just different ways of structuring a solution. The three types of loops can be interchanged, usually with minimal difficulty, but you'll typically find that one more clearly expresses your intent than the other two.

其他提示

The resulting intermediate language may look very similar for both code parts. For was designed to iterate over an indexed object, so if you want to do exactly this, then use it. But you can still do the same thing with while.

From a performance point of view there is no difference. Additionally if you would suffer from performance impact on such a low level you have ruled out any other major performance issue, which in turn would have provided insight on how the IL works here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top