0

I haven't found too much documentation on the differences of the .format() function and f'', My current dilemma is this. I need to cut corners in terms of efficiency where ever I can, this program will be handling very large datasets and I'm out of the 'Just got to make it work stage' so wherever I can drop some CPU usage for the same result I'll take it.

I've tried going to the actual python documentation but wasn't able to find much on it, maybe this is an industry kept secret : o? Anyways, I've also tried print logging every available piece of data on the two and trying to break them in similar ways to see a difference but I haven't been able to tell too much of a difference. Maybe someone knows of a testcase I can use to break a single line format?

Example :

return 'Python3 Is An {} language'.format('Amazing')
x = 'Amazing'
return f'Python3 Is An {x} language'
  • 4
    (1) Don't guess what is faster, use a profiler. (2) The shown f-string won't work, it doesn't tell which variable to include. – Michael Butscher May 01 '23 at 14:54
  • 6
    *"maybe this is an industry kept secret"* Not so much... look for example at https://stackoverflow.com/a/39357545/765091. Briefly, f-strings at one point were slower; they're now faster than `.format`. – slothrop May 01 '23 at 14:54
  • 5
    Don't just go through your codebase and look for things to optimize -- use a profiler to tell you what's taking your CPU time, and focus only on those things. Once you know where your time is going, you can look for microoptimizations as you're doing here -- or you can replace algorithms wholesale with more efficient alternatives; the latter is generally where the substantive gains are. – Charles Duffy May 01 '23 at 15:00
  • One important difference is that f-strings templates are evaluated when they are defined, but string templates that will use `.format()` can be set ahead of time and re-evaluated anytime by calling `.format()` – JonSG May 01 '23 at 15:01

1 Answers1

1

In python the fastest way (from a performance standpoint) to create strings is with fstrings.

According to this benchmark, the format function is over 3.5 times slower than f strings.

Robert Hafner
  • 3,364
  • 18
  • 23