Speed of string += string

Alex Martelli aleax at aleax.it
Sun Apr 13 11:21:42 CEST 2003

achrist at easystreet.com wrote:

> We went around on this one about 4 years ago. Is this a url:

> About 6 messages into the thread, Tim Peters came up with a way that
> was about 5 times faster than string.join().

Not exactly -- the "way" you mention just spreads the costs out,
so they don't SHOW when you're "joining" the pieces (which are
already "joined").  In modern terms:

[alex at lancelot python2.3]$ python -O timeit.py -s'''
import array; SAR=array.array("c")
''' 'for x in data:' ' SAR.fromstring(x)' 'z=SAR.tostring()'
100 loops, best of 3: 2.67e+04 usec per loop

[alex at lancelot python2.3]$ python -O timeit.py -s'''
''' 'z="".join(data)'
100 loops, best of 3: 2.14e+03 usec per loop

Sure, the cost of the .tostring is tiny, but when you have a
lot of little pieces you must loop over them and .fromstring
each -- and THAT is where you're paying the cost.  So .join
is actually an order of magnitude faster...!-)


More information about the Python-list mailing list