def string_times_1(s, n):
return s * n
def string_times_2(s, n):
result = ""
for i in range(n):
result = result + s
return result
def string_times_3(s, n):
"".join(s for _ in range(n))
python -m timeit "100*'string'"
1000000 loops, best of 3: 0.222 usec per loop
python -m timeit "''.join(['string' for _ in range(100)])"
100000 loops, best of 3: 6.9 usec per loop
python -m timeit "result = ''" "for i in range(100):" " result = result + 'string'"
100000 loops, best of 3: 13.1 usec per loop
我对以下三个函数进行了计时:
结果如下:
^{pr2}$正如您所见,
s * n
不仅是最清晰和最简洁的,而且也是最快的。在我们可以使用the ^{} module 来测试:
你可以看到,倍增是更快的选择。您可以注意到,虽然CPython中的字符串连接版本没有那么糟糕,但是may not be true in other versions of Python。因此,您应该始终选择字符串乘法或
str.join()
,不仅要考虑速度,还要考虑可读性和简洁性。在您可以从命令行或代码中使用timeit内容来查看某些python代码的速度有多快:
对你的其他功能做一些类似的事情,并进行比较。在
相关问题 更多 >
编程相关推荐