[英]“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.