F-Strings Speed Considerations & Performance
The f in f-strings may as well stand for “fast.” In this lesson, you’ll see how f-strings are faster than both the %
-formatting and str.format()
00:00
What about speed? f-strings are faster than both %-formatting and str.format()
. At runtime, each expression inside the curly braces gets evaluated within its own scope, and then it’s put together into the final string.
00:14
Let me have you do a few speed comparisons. For this comparison, you’ll need to import timeit
from the standard library, and then create the statement timeit.timeit()
.
00:29
I’ll have you use triple quotes ("""
).
00:34
I’ll have you set the age
. And for the first one, we’ll use %-formatting, so after building the string, percent (%
) then the tuple, ending with the """
, and then a number of times, 10,000 times. Okay.
00:55
Well, what would that look like for .format()
? It would start the same, with name
and age
being set up, but for this one, I’ll have you put your curly braces in, .format(name, age)
.
01:17
End with the """
. And run it 10,000 times also. It took substantially longer. How about the newfangled f-strings? Start the same way, name
and age
.
01:36
And then here, you place name
and age
inside the curly braces.
01:44 I’ll have you put your repeats in, again 10,000 times. f-strings are faster than both of them.
01:55 Let me have you run this one more time, just to check. As you can see, f-strings come out on top—faster than both. It looks like f-strings are pretty great.
02:06 But there are some details you need to keep in mind when using them. Let’s go into those next.
Perryg on July 24, 2020
0.2042874999997366
I think I need a faster CPU!
Become a Member to join the conversation.
Levi on March 14, 2020
Interestingly enough, on my laptop %s clocked in at 0.005390200007241219 and the f strings at 0.0057520999980624765.