Skip to content

Instantly share code, notes, and snippets.

@anapaulagomes
Created February 23, 2018 14:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anapaulagomes/7722c0952b2562e5f89a8d3c952f2a0f to your computer and use it in GitHub Desktop.
Save anapaulagomes/7722c0952b2562e5f89a8d3c952f2a0f to your computer and use it in GitHub Desktop.
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
Copy link
Author

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