我不知道这下面是一个元组(也可用于列表或一个int)做得更快:“不等于”或“大于”更快?
a_tuple = ('a', 'b',)
if (len(a_tuple) != 0): pass
if (len(a_tuple) > 0): pass
我做一些timeit实验,结果非常相似(每次运行timeit进行100000次迭代时都会有所不同)。我只是想知道是否有时间利益。
我不知道这下面是一个元组(也可用于列表或一个int)做得更快:“不等于”或“大于”更快?
a_tuple = ('a', 'b',)
if (len(a_tuple) != 0): pass
if (len(a_tuple) > 0): pass
我做一些timeit实验,结果非常相似(每次运行timeit进行100000次迭代时都会有所不同)。我只是想知道是否有时间利益。
的长度使用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
这样的微观优化很少有益。如果你需要速度,把它外包给C. – Xophmeister