Instantly share code, notes, and snippets.

Embed
What would you like to do?
String interpolation benchmark
# 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}")
@anapaulagomes

This comment has been minimized.

Copy link
Owner

anapaulagomes commented Feb 23, 2018

Results (running on a MacBook Pro 2,8 GHz Intel Core i7 16 GB 1600 MHz DDR3)

f-strings         2.996347602980677
format %          4.152905852010008
concat-strings    5.647188798990101
.format()         5.912839388009161
Template Strings  39.48270317300921
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment