I was playing around with f-strings (see PEP 498), and I decided to check the speed of the f-string parse, (e.g. f"{1}"
) in comparison with the usual str parse (e.g str(1)
). But to my surprise, when I checked the speed of both methods with the timeit function, I found out
that f-strings are faster.
>>> from timeit import timeit
>>> timeit("f'{1}'")
0.1678762999999961
whereas
>>> timeit("str(1)")
0.3216999999999999
or even the repr func, which in most of the cases is faster than str cast
>>> timeit("repr(1)")
0.2528296999999995
I wonder why is that? I thought that the f-strings called str internally, but now, I'm a bit confused, any ideas? Thanks in advance!
PD: Just if anyone is wondering:
assert f"{1}" == str(1) == repr(1)