1

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?

Winston Ewert
  • 44,070
  • 10
  • 68
  • 83

2 Answers2

2

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.

Chris Pitman
  • 12,990
  • 3
  • 41
  • 56
1

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.

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
  • Obviously there are cases where its helpful. What I'm wondering is whether its generally helpful. I have to wonder whether the branch is usually more expensive then what we are avoiding. – Winston Ewert Aug 11 '11 at 17:52
  • The branch isn't expensive. When you think about it, the program calculates the conditions one at a time anyway. There's just 1 extra little boolean check after each condition to see if you can branch out. that costs nothing, and much much less than calling a function. – Yochai Timmer Aug 12 '11 at 07:53
  • but conditional branches are expensive: http://stackoverflow.com/questions/315306/is-if-expensive – Winston Ewert Aug 12 '11 at 16:29
  • "At the very lowest level (in the hardware)" ... And calling a function takes much more than that. There are a lot of calls in storing going on in the process. http://www.unixwiz.net/techtips/win32-callconv-asm.html – Yochai Timmer Aug 12 '11 at 16:58
  • Yes a function will take longer then the branch, but if the second part is simple enough then branching may have been a waste of time. – Winston Ewert Aug 12 '11 at 17:29