Speed of string += string

Daniel Berlin dberlin at dberlin.org
Sun Apr 13 02:52:43 CEST 2003

On Sat, 12 Apr 2003, Mads Orbesen Troest wrote:

> Hi;
> Given that strings are immutable, is it exceedingly slow (and memory
> spiking) to do a lot of "string += string" operations in one's code? IOW,
> does each and every += evaluation lead to a new concatenated copy of the
> previous string (now freed for garbage collection) and the new string, so
> that the longer the string to which stuff is appended is, the longer times
> each += operation takes?

Try the following:

x = ""
for i in xrange(300000):
	x += 'a' * 80


import array
y = array.array('c')
for i in xrange(300000):
	y.fromstring('a' * 80)
x = y.tostring()

You'll find the first one takes minutes, the second, 4 seconds.

More information about the Python-list mailing list