为什么'真或假'比'假或真'更快?

arj*_*onn 3 python optimization time boolean

我运行了代码

a = True
b = False
c = False
d = False
e = False
import time
iterations = int(1e6)
start = time.time()
for _ in range(iterations):
    a or b or c or d or e
print(time.time() - start)
start = time.time()
for _ in range(iterations):
    b or c or d or e or a
print(time.time() - start)
Run Code Online (Sandbox Code Playgroud)

结果

0.10876178741455078
0.26296424865722656
Run Code Online (Sandbox Code Playgroud)
  • 为什么布尔评估的顺序会对速度产生影响?
  • 是因为某种形式的优化?
  • 如果有,我可以阅读资源吗?

Reu*_*ani 6

这是因为短路:

True or WHATEVER # always True
Run Code Online (Sandbox Code Playgroud)

在第一个出现的表达式中a,True没有必要继续进行.

显示这一点的一种很酷的方法是使用一段由于短路而永远不会运行的代码:

>>> def _print():
...     print "no short circuit"
...
>>> True or _print()
True
>>> False or _print()
no short circuit
Run Code Online (Sandbox Code Playgroud)