Given two arbitrary strings:
a = 'start'
b = ' end'
When concatenated they produce 'start end'
What is the fastest way to concatenate the two strings?
Given two arbitrary strings:
a = 'start'
b = ' end'
When concatenated they produce 'start end'
What is the fastest way to concatenate the two strings?
Method 1:
a += b
Method 2:
a + b
Method 3:
''.join((a, b))
Method 4:
'{0}{1}'.format(a, b)
Method 5:
f'{a}{b}'
Method 6:
'%s%s' % (a, b)
We can utilize the timeit
library to test each method.
import timeit
setup: str = 'a = \'start\'\nb = \' end\''
tests: tuple = (
'a += b',
'a + b',
'\'\'.join((a, b))',
'\'{0}{1}\'.format(a, b)',
'f\'{a}{b}\'',
'\'%s%s\' % (a, b)')
number: int = 10000
print(f'Setup:\n{setup}')
times: list = []
for test in tests:
print(f'\nTest: {test}')
time: float = timeit.Timer(test, setup=setup).timeit(number=number)
times.append(str(time))
print(f'Time: {time}')
print('\n\nTimes Side by Side:\n{}'.format('\n'.join(times)))
With this example code, we run each method 10000 times and return the average time it takes.
Setup:
a = 'start'
b = ' end'
Test: a += b
Time: 0.0009844999999999993
Test: a + b
Time: 0.00042200000000003346
Test: ''.join((a, b))
Time: 0.0008056000000000174
Test: '{0}{1}'.format(a, b)
Time: 0.002130199999999971
Test: f'{a}{b}'
Time: 0.00047549999999996206
Test: '%s%s' % (a, b)
Time: 0.0015849000000000002
Times Side by Side:
0.0009844999999999993
0.00042200000000003346
0.0008056000000000174
0.002130199999999971
0.00047549999999996206
0.0015849000000000002
As you can see, Method 2, a + b
is the fastest concatenation method.