Quickest way to concatenate strings

Alan Bawden alan at csail.mit.edu
Fri Oct 12 19:14:05 EDT 2018


"Frank Millman" <frank at chagford.com> writes:
> I have often read that the quickest way to concatenate a number of strings
> is to place them in a list and 'join' them -
> 
>     C:\Users\User>python -m timeit -s "x='a'*500; y='b'*500; z='c'*500"
>     ''.join([x, y, z])
...
> 
> I seem to have found a quicker method, using the new 'f' format operator -
> 
>     C:\Users\User>python -m timeit -s "x='a'*500; y='b'*500; z='c'*500"
>     f'{x}{y}{z}'

If you look at the compiled byte code for the f-string case you'll see why
it's faster: there's nothing used other than opcodes designed specifically
for building strings.

I note that although 'x + y' is faster than f'{x}{y}', 'x + y + z' is
slower than f'{x}{y}{z}'.  Apparently the overhead of making just _one_
temporary intermediate string is enough to tip the balance.  I'm a bit
surprised that it doesn't take a few more than that.  Although I imagine
that that balance might tip at a different point in future releases of
Python (I tested using 3.6.6).

-- 
Alan Bawden



More information about the Python-list mailing list