osdir.com


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

Quickest way to concatenate strings


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).

> 
>  ?? 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: 226 nsec per loop
> 
> Interestingly, the 'format' function is slower -
> 
>  ?? C:\Users\User>python -m timeit -s "x='a'*500; y='b'*500; z='c'*500" 
> '{}{}{}'.format(x, y, z)
>  ?? 500000 loops, best of 5: 559 nsec per loop
> 
> I am using Python 3.7.0 on Windows 10.
> 
> Frank Millman
> 
>