Python f-string benchmarks
Python 3.6 f-strings have been shown to be the fastest string formatting method in microbenchmarks by Python core dev Raymond Hettinger:
#Python's f-strings are amazingly fast!
— Raymond Hettinger (@raymondh) December 14, 2019
f'{s} {t}' # 78.2 ns
s + ' ' + t # 104 ns
' '.join((s, t)) # 135 ns
'%s %s' % (s, t) # 188 ns
'{} {}'.format(s, t) # 283 ns
Template('$s $t').substitute(s=s, t=t) # 898 ns
In relative speed factors, that’s:
- f-string: 1.0
- concatenate string: 1.33
- join sequence of strings: 1.73
- %s formatting operator: 2.40
- .format() method: 3.62
- Template() method: 11.48
The reason for this speedy performance was described by Python core dev Serhiy Storchaka:
1. It can calculate the length and the kind of the resulting string and allocate a memory only once.
— Serhiy Storchaka (@SerhiyStorchaka) December 15, 2019
2. It do not parse the format string at run time.
3. It do not create a tuple, all values are on the stack.
4. It do not look up an attribute and call a method.