我想知道Java中的一些情况(或更一般地说:在编程中),当布尔表达式中首选使用unconditional AND(&)而不是条件版本(&&)时.
我知道它们是如何工作的,但我不能考虑使用单一的情况&是值得的.
def func():
print 'no early termination'
return 0
if __name__ == "__main__":
if 1 or func():
print 'finished'
Run Code Online (Sandbox Code Playgroud)
输出:
finished
Run Code Online (Sandbox Code Playgroud)
因为"1或func()"在没有调用func()的情况下提前终止,因为"1或者某事"总是正确的.但是,当切换到按位运算符时:
def func():
print 'no early termination'
return 0
if __name__ == "__main__":
if 1 | func():
print 'finished'
Run Code Online (Sandbox Code Playgroud)
我得到输出:
no early termination
finished
Run Code Online (Sandbox Code Playgroud)
这是为什么?这看起来效率不高