开发者

Continue loop Inside if statement vs. using the negation of the if statment inside the loop

For example lets consider the following 2 codes:

for (i = 0; i < 1000; i++)
{
   if ( i % 2 != 0)
   {
       continue;
   }
   else
   {
     ...  
   }    
}

and

for (i = 0; i < 1000; i++)
{
   if (i % 2 == 0)
   {
     ...  
   }    
}

Both will lead to the same result. So which one to use? Which one is better? Are there any significant performance differences between the two? Lets see what you guys see about this. I like the discussions I see here about these things. This may lead to better code writing and better execution times. I posted this question because I did not find the answer to it. I may post another one like this in the future if I did not find an 开发者_如何学Canswer to it.

P.S. Whats the purpose of using continue inside a loop when you can go without it?


In this specific example? There's no purpose in using continue whatsoever.

As you mentioned, both code samples produce exactly the same results. And neither will be detectably faster than the other.

The decision you make of which one to prefer should be based on readability and clarity, rather than some type of misguided "optimization" attempt. With that in mind, the second is far clearer. I'd seriously question the programming chops of someone who used the first in a real codebase.

As a basic guideline, never use an if-else when a single if will do. In this case, you're comparing != and then finding the opposite of that with an else statement—that's almost like saying !(!=), which produces a double-negative. Very hard to read or understand. In general, you should try to evaluate positive conditions in an if statement, rather than negative ones, to prevent precisely this.

And there's really no reason to post additional questions that are similar to this one. All of the answers will be the same. Ignore any possible performance difference (if one even exists, which is quite unlikely, given an optimizing compiler), and focus on which version makes the most sense to you as a human being who has to read it. Please ignore anyone who gives you advice to the contrary.


I would definitely not consider the first option since in my opinion it adds uneccessary codepaths to the flow. I do not think it will lead to better results in terms of performance, but if you want to make sure you can examine the IL code.


There will not be enough difference to justify using the ugly form.

Better than either in this specific instance would be

For(i = 0; i < 1000; i+=2)
{
    ...    
}

as there's no need for the divisibility check at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜