Created
December 24, 2016 23:15
-
-
Save perrygeo/3b05fd6a86c28b0813ce5fa40474cb96 to your computer and use it in GitHub Desktop.
Are f-strings or .format faster?
This file contains hidden or 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
#!/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!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: