A few months ago I’ve seen a tweet from a Python learner with a code snippet containing f-strings. I asked, why she’s not using
format() . She answered, that this is the new way of formatting strings. I was curious about it as I didn’t hear about it before. Seeing other people using it, I started to do it as well.
Two weeks ago I spotted a Pull Request on GitHub where somebody used f-strings to convert a value to a string as in the example below.
I was surprised by the usage of f-strings in this particular case. Another user commented to use
str() instead. This conversation led me to the question, which one of both is faster as it was a computationally intensive piece of code.
boxx.timeit showed me the not irrelevant time difference.
“f-strings” spend time: 0.08900404
"str” spend time: 0.160588
Wondering why this is the case? Looking at the byte code gives us the answer. Python provides a module for such cases, the Disassemble-Module. Let’s have a closer look at what’s happening.
The result is shown below.
As you can see the
str_string method consists of one more command (
CALL_FUNCTION). Function calls are expensive and f-strings don’t need to call a separate function.
To summarize f-strings are faster than
str() in terms of converting integers and such types to string. But keep in mind, that we only had a look at simple types. How they perform on more complex types is currently out of my knowledge as I didn’t test it.
Feel free to leave a comment with your own thoughts. Stay curious and keep coding!