我只是编写了一些条件变量,并认为将一个值设置为两个 bool 值之间的相等结果会更容易。
从处理方面来说,什么会更快/更高效,显然这是微不足道的?
bool output = true&true;
或
bool output = true&&true;
我希望后者作为单个相等检查而不是计算整个字节
对之前的含糊之处表示感谢和歉意。从Robbas的回答来看,如果代码类似于:
bool input1 = GenerateFirstValue();
bool input2 = GenerateSecondValue();
bool output = input1 && input2;
一个明显的改进是将前两行放入声明中,这意味着当值为 false 时,您将比按位检查或预设值更有效。特别是当逻辑具有密集方法时。
bool output = GenerateFirstValue() && GenerateSecondValue();
即使这样做,也要按照要求最低的顺序对检查进行排序。
最佳答案
在你假设的例子中,我非常怀疑它是否重要,因为评估 true
非常快(如果没有完全编译)
但是举这个例子:
bool output = veryLongFunction() & otherVeryLongFunction();
对比
bool output = veryLongFunction() && otherVeryLongFunction();
在这种情况下,如果第一个计算结果为 false,则双 && 会使表达式短路,因此比仅使用一个 & 更快。
关于c# - 按位检查和相等检查哪个更有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40524701/