开发者

Looping performance with conditional C#

开发者 https://www.devze.com 2023-02-03 09:22 出处:网络
Which of these will perform better if we assume that the IF block in #1 will be executed more开发者_运维技巧 and less in #2

Which of these will perform better if we assume that the IF block in #1 will be executed more开发者_运维技巧 and less in #2

foreach()
{
if 
{
block here
}
}

or

foreach()
{
if !( )
   continue

}

I've structured #2 to take the if conditional less often. But, i wanted to know if this was necessary or even helpful.


In each case, the condition will be tested. If the condition is "false", then in #1, it will skip to the end of the if block (and hence move to the next foreach item), and in #2, it will execute "continue", which does essentially the same thing.

The frequency of true/false should have no impact on this.


It generates almost exactly the same IL. Even if there was a difference, it would be so minuscule you would not be able to measure a performance delta.

I would choose one by a desire for cleanliness, not performance. The 'continue' keywork, much like the 'break' statement, can often be overlooked by other developers maintaining the code. This is especially true in more verbose foreach loops with lots of code. For this reason I prefer using the nested if then do rather than if ! continue.


Both codes are equivalent.
Don't forget that the CPU will not run your C# code.
First your C# code will be compiled into IL. It is quite possible that both codes will end up producing the same IL.
Then the IL will be compiled into machine code in a CPU-specific way.
Then the CPU will run the machine code instructions out-of-order using branch prediction. It is quite possible that the 'if' costs zero cycle because of the branch prediction.


If you want to do more of a functional approach, pull the conditional completely out of the loop like this (requires Linq):

foreach(var item in MyEnumeration.Where(x=> /* conditional on x */))
{
}
0

精彩评论

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

关注公众号