Speeding up: s += "string"

Roy Smith roy at panix.com
Tue Apr 15 13:56:21 CEST 2003


Lulu of the Lotus-Eaters <mertz at gnosis.cx> wrote:
> If strings were to
> use a preallocation strategy--similar to what lists do--MANY string
> appends could avoid a memory copy on the original string.

I certainly agree that mutable strings would be useful in some 
situations.  For example, in the quadratic run-time program I mentioned 
in a parallel thread, I could easily see doing:

s = ""
s.reserve (len (line))
for word in line.split():
   blah blah blah
   s += stuff

and being very happy that I was now getting linear run time with only a 
trivial change in logic.

The problem is, strings are currently documented as being immutable.  
Making them mutable would break existing code.  I can, for example, find 
the length of a string and use that length someplace later in my 
program, knowing that it hasn't changed.  Not to mention using strings 
as dictionary keys.




More information about the Python-list mailing list