在here之前已经提出过类似的问题,但结论是sum
与len
之间存在差异。在我的测试中,我无法看到是什么让列表理解更快。我正在使用Python 3.4.2,当我加入列表理解与生成器时,我的计算机的性能差异大约为15-20%
我的代码:
import time
def timer(ta=[time.perf_counter()]):
tb, ta[0] = ta[0], time.perf_counter()
return ta[0]-tb
iterations = 10000000
gstr = ''.join(str(i) for i in range(iterations))
print('Generator: {:.3f} s'.format(timer()))
cstr = ''.join([str(i) for i in range(iterations)])
print('List comprehension: {:.3f} s'.format(timer()))
delta = 100-100*ctime/gtime
print()
print('List comprehension is {:.0f} % faster than generator'.format(delta))
输出,即:
Generator: 4.772 s
List comprehension: 3.991 s
List comprehension is 16 % faster than generator
正如评论中所指出的,这是由于str.join()调用了两次项目。解释here但是当删除join()时,差异仍然存在:
gstr = list(str(i) for i in range(iterations))
print('Generator: {:.3f} s'.format(timer()))
lstr = list([str(i) for i in range(iterations)])
print('List of list comprehension: {:.3f} s'.format(timer()))
cstr = [str(i) for i in range(iterations)]
print('List comprehension: {:.3f} s'.format(timer()))
输出:
Generator: 4.088 s
List of list comprehension: 3.720 s
List comprehension: 3.397 s
即使列表清单的新列表仍然更快?