When evaluating if existing code should switch to str.format / f-strings, I found the performance of the old style percentage formatting was around twice as fast.
While I realize the difference might not be important in many cases and the argument for readability over some minor performance difference can always be made. There are times where the difference can matter - dumping large amounts of data to a file for e.g.
Is the test a fair measure of the performance differences between formatting methods in CPython?
Simple timing script:
import time
REPETITIONS = 1_000_000
a, b, c, d, e, f, g, h = [str(a) for a in range(8)]
print("Percentage formatting: '%s'")
t = time.process_time()
for i in range(REPETITIONS):
n = (
"%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s" %
(a, b, c, d, e, f, g, h, a, b, c, d, e, f, g, h)
)
print(time.process_time() - t, '\n')
print("'str.format' formatting: '%s'")
t = time.process_time()
for i in range(REPETITIONS):
n = "{:s} {:s} {:s} {:s} {:s} {:s} {:s} {:s} {:s} {:s} {:s} {:s} {:s} {:s} {:s} {:s}".format(
a, b, c, d, e, f, g, h, a, b, c, d, e, f, g, h,
)
print(time.process_time() - t, '\n')
print("'f-string' formatting: '%s'")
t = time.process_time()
for i in range(REPETITIONS):
n = f"{a:s} {b:s} {c:s} {d:s} {e:s} {f:s} {g:s} {h:s} {a:s} {b:s} {c:s} {d:s} {e:s} {f:s} {g:s} {h:s}"
print(time.process_time() - t, '\n')
With Python 3.8 and 3.9b3 I get similar times, example output.
Percentage formatting: '%s'
1.163297844
String __format__ formatting: '.format()'
1.9792420380000002
F-String formatting: f'...'
2.3670744659999996