osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Quickest way to concatenate strings


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