On Wed, May 14, 2008 at 1:01 AM, Hrvoje Niksic <[EMAIL PROTECTED]> 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
--
http://mail.python.org/mailman/listinfo/python-list