Quickest way to concatenate strings

Frank Millman frank at chagford.com
Fri Oct 12 03:00:40 EDT 2018


On 12/10/2018 08:36, Thomas Jollans wrote:

> On 12/10/2018 07:55, Frank Millman wrote:
> Hi all
> 
> > 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])
> >     500000 loops, best of 5: 307 nsec per loop
> > 
> > I seem to have found a quicker method, using the new 'f' format operator -
> 
> If you know beforehand how many strings you're going to have, you might 
> as well just use (x + y + z).
> 

I tried that, and the ‘f’ operator is still quicker -
C:\Users\User>python -m timeit -s "x='a'*500; y='b'*500; z='c'*500" x+y+z
1000000 loops, best of 5: 374 nsec per loop

C:\Users\User>python -m timeit -s "x='a'*500; y='b'*500; z='c'*500" f'{x}{y}{z}'
1000000 loops, best of 5: 231 nsec per loop

Frank



More information about the Python-list mailing list