String interpolation benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Taken from: https://cito.github.io/blog/f-strings/ | |
import timeit | |
format = """ | |
def format(name, age): | |
return f'He said his name is {name} and he is {age} years old.' | |
""", """ | |
def format(name, age): | |
return 'He said his name is %s and he is %s years old.' % (name, age) | |
""", """ | |
def format(name, age): | |
return 'He said his name is ' + name + ' and he is ' + str( | |
age) + ' years old.' | |
""", """ | |
def format(name, age): | |
return 'He said his name is {} and he is {} years old.'.format(name, age) | |
""", """ | |
from string import Template | |
template = Template('He said his name is $name and he is $age years old.') | |
def format(name, age): | |
return template.substitute(name=name, age=age) | |
""" | |
test = """ | |
def test(): | |
for name in ('Fred', 'Barney', 'Gary', 'Rock', 'Perry', 'Jackie'): | |
for age in range (20, 200): | |
format(name, age) | |
""" | |
methods = ['f-strings', 'format %', 'concat-strings', '.format()', 'Template Strings'] | |
for method, fmt in zip(methods, format): | |
time = timeit.timeit('test()', fmt + test, number=10000) | |
print(f"{method} {time}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results (running on a MacBook Pro 2,8 GHz Intel Core i7 16 GB 1600 MHz DDR3)