Why it is so dramatical?

djw dwelch91 at nospam.attbi.com
Mon Sep 2 18:04:13 EDT 2002


holger krekel wrote:
> 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
> 

Stupid question:

If ""join() is 100-1000 X faster, why doesn't the Python interperter 
translate s = s1 + s2 + ... into s = "".join( [ s1, s2, ... ] ) 
automatically?

Just curious...

D




More information about the Python-list mailing list