javajavascriptccpu-speed

What is faster and best for with if and return or while?


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.


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 :)