我不知道這下面是一個元組(也可用於列表或一個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