String concatenation performance

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Fri May 12 02:16:42 CEST 2006


Cristian.Codorean a écrit :
> I was just reading a "Python Speed/Performance Tips" article on the
> Python wiki
> http://wiki.python.org/moin/PythonSpeed/PerformanceTips
> and I got to the part that talks about string concatenation and that it
> is faster when using join instead of += because of strings being
> immutable.

This is somewhat obsolete. String concatenation have been subject to 
some optimization since 2.3.x (IIRC - else please someone correct me). 
NB: this is only true for CPython.

But the "".join() idiom is, well, still idiomatic...

>  So I have tried it:
> 
> from time import time
> t=time()
> 
> s='almfklasmfkmaskmkmasfkmkqemkmqeqw'
> for x in range(40):
>     #s+= s[len(s)/2:]
>     s="".join((s,s[len(s)/2:]))

Lol...

I'm afraid you didn't get the idiom right. The point is to avoid useless 
allocations in the loop body. The idiom is:

buf = []
for x in range(42):
   buf.append(s)
s = "".join(buf)

> print 'duration', time() - t

timeit may be a better choice for microbenchmarks.




More information about the Python-list mailing list