Why is Python's 'len' function faster than the __len__ method?

那年仲夏 提交于 2019-12-18 03:57:14

问题


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?


回答1:


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.




回答2:


__len__ is slower than len(), because __len__ involves a dict lookup.



来源:https://stackoverflow.com/questions/20302558/why-is-pythons-len-function-faster-than-the-len-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!