String += time trials. (was: Re: Speeding up: s += "string")

Erik Max Francis max at alcyone.com
Fri May 9 17:15:31 EDT 2003


Francis Avila wrote:

> Is it the best solution?

My point was that naive string concatenation inside a loop brings out
the worst behavior (O(n^2)), and was suggesting a solution that has
better scaling (amortized O(n)).  StringIO/cStringIO would also be an
example of a way to get this superior behavior.

As for the specific merits of building a list and then using S.join vs.
StringIO, that really depends on the specifics of the situation.  I
don't know how helpful your comparison here is, since you're dealing
with such tiny strings.

My point would simply be to pick the behavior that has the right big-O
complexity.  In a language like Python, you're not looking to optimize
every last cycle out of your program -- otherwise you wouldn't be using
Python -- but you _do_ want to make sure that your program uses the
proper algorithms to prevent complexity explosions.  Repeated string
concatenation is bad.  The other solutions are good.  The relative
goodness of the superior solutions is something I wouldn't worry about
too much.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The critical period in matrimony is breakfast-time.
\__/ A.P. Herbert
    Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/
 A personal guide to Aliens vs. Predator 2.




More information about the Python-list mailing list