在分析我的Python应用程序时,我发现len()使用集合时似乎非常昂贵.请参阅以下代码:
import cProfile
def lenA(s):
for i in range(1000000):
len(s);
def lenB(s):
for i in range(1000000):
s.__len__();
def main():
s = set();
lenA(s);
lenB(s);
if __name__ == "__main__":
cProfile.run("main()","stats");
Run Code Online (Sandbox Code Playgroud)
根据profiler的统计数据,lenA()似乎比lenB()以下慢14倍:
ncalls tottime percall cumtime percall filename:lineno(function)
1 1.986 1.986 3.830 3.830 .../lentest.py:5(lenA)
1000000 1.845 0.000 1.845 0.000 {built-in method len}
1 0.273 0.273 0.273 0.273 .../lentest.py:9(lenB)
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?目前我使用__len__()而不是len(),但代码看起来很脏:(