list.__len__() or len(list)

Christian Heimes lists at cheimes.de
Tue May 13 21:14:42 EDT 2008


Ian Kelly schrieb:
> The purpose of obj.__len__() is to implement len(obj), which simply
> calls it.  So obj.__len__() may be faster, but only marginally.  The
> reason to prefer len(obj) is that if you inadvertently pass an object
> that does not implement __len__, you get the more appropriate
> TypeError rather than an AttributeError.

len(obj) is faster than obj.__len__() for several types like str. In
general len() is as least as fast __len__(). len() also does some extra
sanity checks.

python2.5 -m timeit "'abc'.__len__()"
1000000 loops, best of 3: 0.453 usec per loop

python2.5 -m timeit "len('abc')"
1000000 loops, best of 3: 0.292 usec per loop

Common code paths are already highly optimized. Don't try to be clever
unless you really understand what happens inside the interpreter. The
__internal__ methods are called magic methods for a reason. ;)

Christian




More information about the Python-list mailing list