In Python, len
is a function to get the length of a collection by calling an object's __len__
method:
def len(x):
return x.__len__()
So I would expect direct call of __len__()
to be at least as fast as len()
.
import timeit
setup = '''
'''
print (timeit.Timer('a="12345"; x=a.__len__()', setup=setup).repeat(10))
print (timeit.Timer('a="12345"; x=len(a)', setup=setup).repeat(10))
Demo link
But results of testing with the above code shows len()
to be faster. Why?