list.__len__() or len(list)

Hrvoje Niksic hniksic at xemacs.org
Wed May 14 10:56:55 EDT 2008


"Ian Kelly" <ian.g.kelly at gmail.com> writes:

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

Well, he did ask about list.  :-)

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

Yes, in that case the C slot contains a generic wrapper that still has
to locate and call the Python function, which ends up being slower.
The point is that such microoptimizations rarely make a difference,
and even then the difference can be counterintuitive, as in the list
example.



More information about the Python-list mailing list