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?