In Python, len
is a function to get the length of a collection by calling an object’s __len__
method:
JavaScript
x
3
1
def len(x):
2
return x.__len__()
3
So I would expect direct call of __len__()
to be at least as fast as len()
.
JavaScript
1
8
1
import timeit
2
3
setup = '''
4
'''
5
6
print (timeit.Timer('a="12345"; x=a.__len__()', setup=setup).repeat(10))
7
print (timeit.Timer('a="12345"; x=len(a)', setup=setup).repeat(10))
8
But results of testing with the above code shows len()
to be faster. Why?
Advertisement
Answer
The builtin len()
function does not look up the .__len__
attribute. It looks up the tp_as_sequence
pointer, which in turn has a sq_length
attribute.
The .__len__
attribute on built-in objects is indirectly mapped to the same slot, and it is that indirection (plus the attribute lookup) that takes more time.
For Python-defined classes, the type
object looks up the .__len__
method when the sq_length
is requested.