我看过很多帖子(例如 here 和 here)谈论 Python 中的连接,如何最好地做到这一点('+' vs ','),哪个更快,等等。但是我似乎无法找出为什么它很重要。 Roger Pate 在第一个例子中提到了关于传递多个参数与一个参数,但我仍然不清楚。
那么,为什么串联很重要?这在什么情况下很重要?
请您参考如下方法:
因为通常 +ing n 字符串将导致 n-1 分配 O(n)结果的内存。通过邻接的连接在解析器中完成,并执行 1 次分配。通过例如 ''.join(iter(s)) 的连接将执行 O(log(n)) 分配/副本 2n 总计内存。
> a = ['a'] * 100000
> def concat(strings):
c = ''
for s in strings:
c += s
return c
> %timeit ''.join(a) # precalculates necessary buffer size
1000 loops, best of 3: 1.07 ms per loop
> %timeit ''.join(iter(a)) # allocates exponentially larger buffers
1000 loops, best of 3: 1.94 ms per loop
> %timeit concat(a) # allocates a new buffer n-1 times
100 loops, best of 3: 7.15 ms per loop
