Hacker News new | ask | show | jobs
by solveit 1957 days ago
>what is the point ?

I can see an in-house style guide strongly recommending f-strings over % formatting

1 comments

Also can improve performance.
Sure, but how often is string formatting the bottleneck on performance?
Do you have a proof of that? I think that it might be the opposite.
F-strings are much faster:

    In [4]: a, b, c, d = ("123", "456", "789", "0ab")

    In [5]: %timeit a + "-" + b
    139 ns ± 10 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

    In [6]: %timeit "%s-%s" % (a, b)
    198 ns ± 13.8 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

    In [7]: %timeit "{}-{}".format(a, b)
    248 ns ± 9.17 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

    In [8]: %timeit f"{a}-{b}"
    99 ns ± 2.48 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

    In [9]: %timeit  a + "-" + b + "-" + c + "-" + d
    344 ns ± 10.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

    In [11]: %timeit "%s-%s-%s-%s" % (a, b, c, d)
    290 ns ± 9.64 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

    In [12]: %timeit ''.join([a, '-', b, '-', c, '-', d])
    245 ns ± 2.32 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

    In [13]: %timeit "{0}-{1}-{2}-{3}".format(a, b, c, d)
    471 ns ± 23.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

    In [14]: %timeit f"{a}-{b}-{c}-{d}"
    176 ns ± 11.9 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
It’s not a proof, but it makes logical sense: f-strings can be noted and compiled at runtime, whereas regular strings must be compiled every time string.format notices them. Maybe middling on one run, but reasonably useful in a long loop