开发者

Short Circuiting and Performance

开发者 https://www.devze.com 2023-03-26 23:45 出处:网络
Most language use short-circuited and/or operators. For example return foo() && bar(); will never call bar() if foo() returns false. There is no need to call bar() if we know that the resul

Most language use short-circuited and/or operators. For example

return foo() && bar();

will never call bar() if foo() returns false. There is no need to call bar() if we know that the result of the expression will be false anyways.

Presumably, this behavior was originally implemented in order to 开发者_如何学编程make code run faster. However, technology has changed since then. In particular branches are more expensive relative to other operations then would have been the case when short-circuiting was introduced.

So I'm wondering: is it still a performance gain to short circuit operators?


The answer should be "maybe".

Take a look at this blog by Eric Lippert on some of the low level optimizations done by the C# compiler.

He argues that, at the very least, short circuiting the evaluation of a simple boolean expression is more expensive that just evaluating the entire thing. Here is the relevant excerpt:

A brief aside: shouldn’t that be temp1.HasValue && temp2.HasValue? Both versions give the same result; is the short circuiting one more efficient? Not necessarily! AND-ing together two bools is extremely fast, possibly faster than doing an extra conditional branch to avoid what is going to be an extremely fast property lookup. And the code is certainly smaller. Roslyn uses non-short-circuiting AND, and I seem to recall that the earlier compilers do as well.


yes.

Think about it, what if you want to do something like this:

return IsOKToStart() && CalculateFirstPrimeGreaterThanTrilion();

the first one is a simple test, the other will still take a few months to calculate.

0

精彩评论

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

关注公众号