list.__len__() or len(list)

Ian Kelly ian.g.kelly at gmail.com
Wed May 14 09:29:33 EDT 2008


On Wed, May 14, 2008 at 1:01 AM, Hrvoje Niksic <hniksic at xemacs.org> wrote:
>  Have you tried it?  __len__ is in fact marginally slower because it
>  involves a dict lookup, whereas the built-in len() knows how to cheat
>  and invoke __len__ through a slot in the C type struct very
>  efficiently.
>
>  $ python -m timeit -s 'l=[1, 2, 3]' 'len(l)'
>  1000000 loops, best of 3: 0.24 usec per loop
>  $ python -m timeit -s 'l=[1, 2, 3]' 'l.__len__()'
>  1000000 loops, best of 3: 0.347 usec per loop

For built-in types, sure.  For user-defined types in Python, it's the
other way around:

>>> setup = 'class L:\n  def __len__(self): return 42\nl = L()'
>>> t1 = timeit.Timer('len(l)', setup)
>>> t2 = timeit.Timer('l.__len__()', setup)
>>> t1.timeit()
0.63981378918270337
>>> t2.timeit()
0.41051271879526041



More information about the Python-list mailing list