列表理解比PyPy3中的索引访问创建列表要慢得多



我用Bash的时间函数测试了下面的代码
为什么PyPy3中的列表理解不快,尽管它是CPython中创建列表最快的
这是因为PyPy3中为索引访问实现了一些优化吗?

# test_list_compr.py
import os

def main():
n = 10 ** 8
lis = [i * 2 for i in range(n)]
print(sum(lis), file=open(os.devnull, mode="w"))

if __name__ == "__main__":
main()
# test_list_for.py
import os

def main():
n = 10 ** 8
lis = []
for i in range(n):
lis.append(i * 2)
print(sum(lis), file=open(os.devnull, mode="w"))

if __name__ == "__main__":
main()
# test_list_index.py
import os

def main():
n = 10 ** 8
lis = [0] * n
for i in range(n):
lis[i] = i * 2
print(sum(lis), file=open(os.devnull, mode="w"))

if __name__ == "__main__":
main()
Results:
python3 test_list_compr.py  8.09s user 2.10s system 96% cpu 10.522 total
python3 test_list_for.py  11.62s user 1.76s system 89% cpu 15.009 total
python3 test_list_index.py  9.46s user 1.56s system 89% cpu 12.316 total
pypy3 test_list_compr.py  2.51s user 2.27s system 87% cpu 5.445 total
pypy3 test_list_for.py  2.39s user 2.17s system 99% cpu 4.603 total
pypy3 test_list_index.py  0.49s user 0.19s system 98% cpu 0.694 total
Env:
CPython3 (3.8.2), PyPy3 (7.3.0)

更新
根据mattip的评论,我将PyPy3更新到v7.3.1,列表理解的性能显著提高
我感谢PyPy的开发人员!

Results:
pypy3 test_list_compr.py  0.54s user 0.27s system 97% cpu 0.830 total
pypy3 test_list_for.py  2.74s user 2.49s system 94% cpu 5.530 total
pypy3 test_list_index.py  0.53s user 0.27s system 71% cpu 1.115 total

如问题的Update部分所述,在7.3.1中,列表理解效果很快。

最新更新