I've downloaded a Python 3.6 alpha build from the Python Github repository, and one of my favourite new features is literal string formatting. It can be used like so:
>>> x = 2
>>> f"x is {x}"
"x is 2"
This appears to do the same thing as using the format
function on a str
instance. However, one thing that I've noticed is that this literal string formatting is actually very slow compared to just calling format
. Here's what timeit
says about each method:
>>> x = 2
>>> timeit.timeit(lambda: f"X is {x}")
0.8658502227130764
>>> timeit.timeit(lambda: "X is {}".format(x))
0.5500578542015617
If I use a string as timeit
's argument, my results are still showing the pattern:
>>> timeit.timeit('x = 2; f"X is {x}"')
0.5786435347381484
>>> timeit.timeit('x = 2; "X is {}".format(x)')
0.4145195760771685
As you can see, using format
takes almost half the time. I would expect the literal method to be faster because less syntax is involved. What is going on behind the scenes which causes the literal method to be so much slower?
Note: This answer was written for the Python 3.6 alpha releases. A new opcode added to 3.6.0b1 improved f-string performance significantly.
The
f"..."
syntax is effectively converted to astr.join()
operation on the literal string parts around the{...}
expressions, and the results of the expressions themselves passed through theobject.__format__()
method (passing any:..
format specification in). You can see this when disassembling:Note the
BUILD_LIST
andLOAD_ATTR .. (join)
op-codes in that result. The newFORMAT_VALUE
takes the top of the stack plus a format value (parsed out at compile time) to combine these in aobject.__format__()
call.So your example,
f"X is {x}"
, is translated to:Note that this requires Python to create a list object, and call the
str.join()
method.The
str.format()
call is also a method call, and after parsing there is still a call tox.__format__('')
involved, but crucially, there is no list creation involved here. It is this difference that makes thestr.format()
method faster.Note that Python 3.6 has only been released as an alpha build; this implementation can still easily change. See PEP 494 – Python 3.6 Release Schedule for the time table, as well as Python issue #27078 (opened in response to this question) for a discussion on how to further improve the performance of formatted string literals.
Before 3.6 beta 1, the format string
f'x is {x}'
was compiled to the equivalent of''.join(['x is ', x.__format__('')])
. The resulting code was inefficient for several reasons:join
method on the empty string__format__
on even bare Unicode objects, for which the__format__('')
would always returnself
, or integer objects, for which__format__('')
as the argument returnedstr(self)
.__format__
method isn't slotted.However, for a more complex and longer string, the literal formatted strings would still have been faster than the corresponding
'...'.format(...)
call, because for the latter the string is interpreted every time the string is formatted.This very question was the prime motivator for issue 27078 asking for a new Python bytecode opcode for string fragments into a string (the opcode gets one operand - the number of fragments on the stack; the fragments are pushed in in reverse order, i.e. the last part is the topmost item). Serhiy Storchaka implemented this new opcode and merged it into CPython so that it has been available in Python 3.6 ever since beta 1 version (and thus in Python 3.6.0 final).
As the result the literal formatted strings will be much faster than
string.format
. They are also often much faster than the old-style formatting in Python 3.6, if you're just interpolatingstr
orint
objects:f'X is {x}'
now compiles toThe new
BUILD_STRING
, along with an optimization inFORMAT_VALUE
code completely eliminates first 5 of the 6 sources of inefficiency. The__format__
method still isn't slotted, so it requires a dictionary lookup on the class and thus calling it is necessarily slower than calling__str__
, but a call can now be completely avoided in the common cases of formattingint
orstr
instances (not subclasses!) without formatting specifiers.