C#:编译器优化,函数调用和布尔表达式短路

Bra*_*ins 2 c# optimization short-circuiting boolean-operations

我们假设我们有以下昂贵的功能:

bool ExpensiveOp1() { ... }
bool ExpensiveOp2() { ... }
bool ExpensiveOp3() { ... }
Run Code Online (Sandbox Code Playgroud)

另外,为了简单起见,假设它们都没有副作用.

我知道C#可以短路if ExpensiveOp1ExpensiveOp2返回false以下表达式:

return ExpensiveOp1() && ExpensiveOp2() && ExpensiveOp3();
Run Code Online (Sandbox Code Playgroud)

但是,如果我以这种方式编写代码,编译器是否足够智能(缺少更好的术语)内联函数调用并利用短路?

var x = ExpensiveOp1();
var y = ExpensiveOp2();
var z = ExpensiveOp3();
return x && y && z;
Run Code Online (Sandbox Code Playgroud)

Tur*_*ama 5

不,并且有充分的理由.编译器不知道您的任何操作是否有副作用,因此如果您在布尔短路情况之外运行它们,它会运行它们以防您有所需的副作用.

  • @BradCollins你可以很容易地自己测试它.请参阅https://dotnetfiddle.net/nunVOV (2认同)