DEV Community

TildAlice
TildAlice

Posted on • Originally published at tildalice.io

f-strings vs % Formatting: When Old Syntax Wins 2.1x Speed

The Benchmark That Made Me Question Everything

Run this on Python 3.11 and watch what happens:

import timeit

# f-string version
def fstring_format():
    x = 42
    return f"Value: {x}"

# % formatting version
def percent_format():
    x = 42
    return "Value: %d" % x

print(f"f-string: {timeit.timeit(fstring_format, number=10_000_000):.3f}s")
print(f"% format: {timeit.timeit(percent_format, number=10_000_000):.3f}s")
Enter fullscreen mode Exit fullscreen mode

On my machine (M1 MacBook, Python 3.11.7), f-strings take 0.847s while % formatting finishes in 0.401s. That's 2.1x faster for the "legacy" syntax.

Wait, what?

Every tutorial since PEP 498 (Python 3.6) has told us f-strings are faster. The official docs say they're "a way to embed expressions inside string literals, using a minimal syntax." Most benchmarks show f-strings crushing .format() and % formatting. So why does this simple case flip the script?

Artistic close-up of a violin on sheet music, highlighting musical elegance.

Photo by Ylanite Koppens on Pexels

Why f-strings Are Usually Faster (And When That Breaks)


Continue reading the full article on TildAlice

Top comments (0)