Skip to content

Instantly share code, notes, and snippets.

@perrygeo
Created December 24, 2016 23:15
Show Gist options
  • Save perrygeo/3b05fd6a86c28b0813ce5fa40474cb96 to your computer and use it in GitHub Desktop.
Save perrygeo/3b05fd6a86c28b0813ce5fa40474cb96 to your computer and use it in GitHub Desktop.
Are f-strings or .format faster?
#!/usr/bin/env python3.6
import time
n = 1_000_000
print("Using .format")
start = time.time()
template = "This is a new {thing} with {x} properties"
for thing, x in zip('abcdefghijklmnopqrstuvwxyz' * int(n/26), range(n)):
_ = template.format(thing=thing, x=x)
end = time.time()
elapsed_format = end - start
print(elapsed_format)
print("Using f-strings")
start = time.time()
for thing, x in zip('abcdefghijklmnopqrstuvwxyz' * int(n/26), range(n)):
_ = f"This is a new {thing} with {x} properties"
end = time.time()
elapsed_fstring = end - start
print(elapsed_fstring)
ratio = elapsed_format / elapsed_fstring
print(f"f-strings are {ratio:0.2f} times faster!")
@perrygeo
Copy link
Author

Results:

Using .format
0.9278731346130371
Using f-strings
0.37136220932006836
f-strings are 2.50 times faster!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment