简体   繁体   中英

“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) :

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). 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:

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:

>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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