Continue the loop Inside the if statement or by negating the if state inside the loop

For example, 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 significant performance differences between the two? Let's see what you guys see about this. I like the discussions I see here about these things. This can lead to better coding and better runtime. I posted this question because I could not find an answer to it. I can publish another similar one in the future if I cannot find an answer to it.

PS What is the purpose of using continuation within a loop when you can do without it?

+4
source share
3 answers

In this particular example? It makes no sense to use continue at all.

As you mentioned, both code examples give exactly the same results. And not one of them will detect faster than the other.

The decision that you make, prefer, should be based on readability and clarity , and not on an attempt to optimize. With this in mind, the second is much clearer. I seriously doubt the programming of chops from those who used the first in a real code base.

As a basic guide, never use if-else when a single if will be executed. In this case, you compare != , And then find the opposite value with the else expression, which is almost like saying !(!=) , Which produces double negation. It is very difficult to read or understand. In general, you should try to evaluate the positive conditions in the if rather than the negative ones to prevent this from happening.

And there is no reason to post additional questions similar to this. All answers will be the same. Ignore any possible difference in performance (if it even exists, which is unlikely, given the optimizing compiler), and focus on which version is best for you as the person who needs to read it. Please ignore anyone who advises you otherwise.

+5
source

I would definitely not consider the first option, because, in my opinion, it adds raw code files to the stream. I do not think that this will lead to better results in terms of performance, but if you want to make sure you can check the IL code.

0
source

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

Better than in this particular case will be

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

since there is no need to check for divisibility.

-1
source

All Articles