问题描述
我有一堆都返回布尔值的方法.
I have a bunch of methods that all return a bool.
如果一个方法返回false,则调用以下方法没有任何价值,尤其是其中一些是昂贵"的操作.
If one method returns false then there is no value in calling the following methods, especially as some of them are 'expensive' operations.
哪个效率更高?
bool result = method1();
if (result) result = method2();
if (result) result = method3();
return result;
或
return method1() && method2() && method3();
据我了解,一旦其中一种方法返回false,对第二种形式应该立即停止评估,对吧?
As I understand it, the 2nd form should stop evaluating as soon as one of the methods returns false, right?
推荐答案
是的,您是对的.均&&&和||c#中的布尔运算符用作短路运算符.确定表达式的值后,它将停止评估表达式.它停止不必要的执行.
Yes you are right. Both && and || boolean operators in c# work as short-circuit operator. It stops evaluating expression once its value is determined. It stops unnecessary execution.
因此,返回方法1()&&method2()&&在您的情况下,method3();
是更好的选择.如果您有未评估的语句中的某些内容,例如您的情况下说method3,可能会导致一些副作用.
Hence return method1() && method2() && method3();
is better option in your case. If you have something in non-evaluated statement, say method3 in your case, it may lead to some side effects.
Wikipedia 上有一篇关于短路操作员的非常好的语言独立文章.
There is this very good language independent article about short-circuit operators on Wikipedia.
更新:在C#中,如果要使用逻辑运算符而不发生短路,请使用&和|运算符.
UPDATE:In C# if you want to use logical operator without short-circuit, use & and | operator instead.
这篇关于&&的链接方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!