← Back to context

Comment by CmdrKrool

20 hours ago

I'm confused by this:

  String operations in Python are fast as well. f-strings are the fastest formatting style, while even the slowest style is still measured in just nano-seconds.
  
  Concatenation (+)   39.1 ns (25.6M ops/sec)
  f-string            64.9 ns (15.4M ops/sec)

It says f-strings are fastest but the numbers show concatenation taking less time? I thought it might be a typo but the bars on the graph reflect this too?

String concatenation isn't usually considered a "formatting style", that refers to the other three rows of the table which use a template string and have specialized syntax inside it to format the values.

Perhaps it's because in all but the simplest cases, you need 2 or more concatenations to achieve the same result as one single f-string?

  "literal1 " + str(expression) + " literal2"

vs

  f"literal1 {expression} literal2"

The only case that would be faster is something like: "foo" + str(expression)