compare and with all

关于 and 和 all 这个主题,起初是在公司论坛里看到一个性能优化的分享

用 a==a and b==b 替换 all([a == a, b == b]),然后接口 P95 从 110ms 降到了 65ms

但是实际准备动手自己实验,还是是受 wen 文章 的影响,对技术充满好奇并去实验尝试和拓展是学好东西的非常重要的环节。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import time

start = time.time()
count = 0

def func():
return True


while True:
if time.time() - start >= 1:
print 'count:', count
break
count += 1
# all((True == True, True == True)) # count: 1839213
True == True and True == True # count: 2398995

从上面的实验说明,在相同时间下,使用 and 的方式比 all 执行的次数更多,也就是 and 在这样的场景下,效率更高。

从官方文档里面看到,all 是约等于下面的实现 https://docs.python.org/3/library/functions.html#all

也就是 all 对每个 element 都会去计算,但是 and 会 lazy 的去算,前一个不成立了后面就不执行了。

1
2
3
4
5
def all(iterable):
for element in iterable:
if not element:
return False
return True
The preferred syntax for initializing a dictionary
Python SocketServer 源码阅读