by ejiblabahaba · 1y ago · 0 comments
F-strings are great, but trying to remember the minute differences between string interpolation, old-style formatting with %, and new-style formatting with .format(), is sort of a headache, and there's cases where it's unavoidable to switch between them with some regularity (custom __format__ methods, templating strings, logging, etc). It's great that there's ergonomic new ways of doing things, which makes it all the more frustrating to regularly have to revert to older, less polished solutions.
Yes: https://docs.python.org/3/whatsnew/3.12.html#whatsnew312-pep...
The reason is that focusing on formatting CPU performance misses a bigger issue: memory thrashing.
There are a surprisingly large number of places in the average log-happy program where the arguments to the logger format string can be unexpectedly large in uncommon-but-not-astronomically-improbable situations.
When the amount of memory needed to construct the string to feed down into the logger (even if nothing is done with it due to log levels) is an order of magnitude or two bigger than the usual less-than-1kb log line, the performance cost of allocating and freeing that memory can be surprising—surprising enough to go from “only tight number crunching loops will notice overhead from logger formatting” to “a 5krps fast webhook HTTP handler that calls logger.debug a few times with the request payload just got 50% slower due to malloc thrashing”.
Bottom line, still a micro optimization on a modern machine in the vast majority of cases.
If you have a truly costly format op and still want to use fstring, look into .isEnabledFor().