Brad Collins
Brad Collins

Reputation: 876

C#: Compiler optimization, function calls, and Boolean expression short-circuiting

Let's assume that we have the following expensive functions:

bool ExpensiveOp1() { ... }
bool ExpensiveOp2() { ... }
bool ExpensiveOp3() { ... }

Also, to keep it simple, assume that none of them have side effects.

I know that C# can short-circuit if ExpensiveOp1 or ExpensiveOp2 returns false in the following expression:

return ExpensiveOp1() && ExpensiveOp2() && ExpensiveOp3();

However, is the compiler smart enough to (for lack of a better term) inline the function calls and take advantage of short-circuiting if I write the code this way?

var x = ExpensiveOp1();
var y = ExpensiveOp2();
var z = ExpensiveOp3();
return x && y && z;

Upvotes: 2

Views: 159

Answers (1)

Turksarama
Turksarama

Reputation: 1136

No, and for a good reason. The compiler doesn't know if any of your operations have side effects, so if you run them outside of a boolean short circuiting situation it runs them in case there are side effects you want.

Upvotes: 5

Related Questions