python - 为什么 'True or False' 比 'False or True' 快?

标签 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)

结果

0.10876178741455078
0.26296424865722656
  • 为什么 boolean 运算的顺序会影响速度?
  • 是因为某种形式的优化吗?
  • 如果有,是否有我可以阅读的资源?

最佳答案

这是因为 short-circuiting :

True or WHATEVER # always True

在第一个表达式 a 中,True 出现在第一位,无需继续。

展示这一点的一个很酷的方法是使用一段因短路而永远不会运行的代码:

>>> def _print():
...     print "no short circuit"
...
>>> True or _print()
True
>>> False or _print()
no short circuit

关于python - 为什么 'True or False' 比 'False or True' 快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32474452/

相关文章:

python - time.strftime() 不更新

linux - 如何加速 Linux 内核编译?

mysql - 优化 MySQL 数据库索引 InnoDB

python - pytorch中的外和等

c++ - 如何在 clang++ 中禁用矢量化?

javascript - 通过 AJAX 发布 Django 表单集

Java 日期到毫秒

python - 如何在 Python 中查找开放阅读框

python - 按 date_range 从 DataFrame 中选择行

python - 使用 BeautifulSoup 根据其中包含的字符串提取 li 元素