Question

I have a question about the for and while loops, as we have to travel a value until a condition is met. I wonder which is more efficient at low level, and why?

That is, these two codes give the same result:

FOR:

for (int i = 0; i<10 ; i++)
{
    if (i==4)
    {
        return;
    }
}

WHILE:

int i=0;
while (i<10 and i!=4)
{
    i++;
}

This is a small example of a possible loop, and we could be looking at a record of thousands.

What code is more effective? I've always said that I have to use a while in this case, but I wonder if a low level is still better while or better yet is for.

Thank you very much.

Was it helpful?

Solution

The answer is: it doesn't matter.

You will not see any difference in performance in either, unless you really try hard to make code to see the difference, and what really matters is the readability of your code (and this is where you'll save time and and money in the future), so use whichever one is more understandable.

In your case, i'll suggest the While approach ...


I'll also suggest reading this article by Eric Lippert: How Bad Is Good Enough?, just in case you're not sold on the readability vs. silly optimizations :)

OTHER TIPS

They should compile very similarly. At a low level you are looking at executing the commands within the loop, and then you will have two calls to compare a value and jump to the next block of code if the condition calls for exiting the loop.

As mentioned above, while should lead to better readability and thus is the better choice.

Both for and while are the same.

The only difference is where you place the condition. internally the while loop uses the 'for' syntax in low level.

In your scenario. While is the best option ** if you don't know the upper limit **

you can use

While(i!=4)
{
 i++
}

Use for loop if you know the upper limit, else while is the best friend.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top