简体   繁体   English

“不等于”或“大于”更快吗?

[英]“Non-equal” or “greater than” is quicker?

I wonder which of the following is done quicker for a tuple (also for a list or an int) : 我想知道对于元组(对于列表或int),以下哪一项可以更快地完成:

a_tuple = ('a', 'b',)
  1. if (len(a_tuple) != 0): pass

  2. if (len(a_tuple) > 0): pass

I did some timeit experiment and the result is rather similar (vary each time I run timeit for 100000 iterations). 我做了一些timeit实验,结果非常相似(每次运行timeit进行100000次迭代时都会有所不同)。 I just wonder if there is a time benefit. 我只是想知道是否有时间上的好处。

Use not a_tuple ( True if empty) or tuple ( True if not empty) instead of testing for the length: 使用not a_tuple (如果为空not a_tuple True )或tuple (如果不为空则为True )而不是测试长度:

if a_tuple:
    pass

Or, as a demonstration speaks louder than words: 或者,就像一个示范胜于雄辩:

>>> if not ():
...     print('empty!')
...
empty!
>>> if (1, 0):
...     print('not empty!')
...
not empty!

Apart from the fact that this is a micro optimization, testing for the falsy-ness of the empty tuple is faster too. 除了这是一个微优化之外,对空元组的虚假性的测试也更快。 When in doubt about speed, use the timeit module: 如果对速度有疑问,请使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM