[英]“Non-equal” or “greater than” is quicker?
我想知道对于元组(对于列表或int),以下哪一项可以更快地完成:
a_tuple = ('a', 'b',)
if (len(a_tuple) != 0): pass
if (len(a_tuple) > 0): pass
我做了一些timeit实验,结果非常相似(每次运行timeit进行100000次迭代时都会有所不同)。 我只是想知道是否有时间上的好处。
使用not a_tuple
(如果为空not a_tuple
True
)或tuple
(如果不为空则为True
)而不是测试长度:
if a_tuple:
pass
或者,就像一个示范胜于雄辩:
>>> if not ():
... print('empty!')
...
empty!
>>> if (1, 0):
... print('not empty!')
...
not empty!
除了这是一个微优化之外,对空元组的虚假性的测试也更快。 如果对速度有疑问,请使用timeit
模块:
>>> import timeit
>>> a_tuple = (1,0)
>>> def ft_bool():
... if a_tuple:
... pass
...
>>> def ft_len_gt():
... if len(a_tuple) > 0:
... pass
...
>>> def ft_len_ne():
... if len(a_tuple) != 0:
... pass
...
>>> timeit.timeit('ft()', 'from __main__ import ft_bool as ft')
0.17232918739318848
>>> timeit.timeit('ft()', 'from __main__ import ft_len_gt as ft')
0.2506139278411865
>>> timeit.timeit('ft()', 'from __main__ import ft_len_ne as ft')
0.23904109001159668
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.