Why it is so dramatical?

holger krekel pyth at devel.trillke.net
Mon Sep 2 06:03:44 EDT 2002


Bo M. Maryniuck wrote:
> The task:
> 	Adding a text to a text.
> 
> The problem:
> 	It is tragically slow to add string to huge string.

That's because strings are immutable objects. When you issue

    somestring += otherstring

a new string object is allocated where the contents of
somestring and otherstring are copied in.  Then the
name 'somestring' is bound to this new string.

If you have something like this in a loop it's often
*much* better to work with a list and later do a 

    "".join(stringlist)

As you observed yourself this is around 100-1000 times faster.  

And consider: if strings were not immutable but modified in-place
(like lists) you couldn't use them as dictionary keys. 

if-it-hurts-don't-do-it-ly, yours Holger




More information about the Python-list mailing list