Fastest alternative to `format!`

I heard that format! is slow compared to the alternatives. What is the fastest alternative to format!? Is format! really that slow? I didn't notice any difference in execution time when I replaced a format! with multiple calls to .push(..) and .push_str(..)

“ format! is slow compared to the alternatives” is just a gross oversimplification. What does format! do? It “creates a String using interpolation of runtime expressions”. Notably, it

  • creates a new String
  • from run-time values that implement formatting traits such as Display or Debug, and
  • supports the flexible syntax of formatting expressions

Is there any “alternative” that does the same thing but faster? Of course not! Functionality from the standard library is never deliberately slower than necessary.

Given some usages of format! that don’t actually benefit from all the abilities of format!, are there sometimes ways to make those faster? Of course! To give a stupid example, if you want to know the number of digits in a u8, then format!("{n}").len() is of course slower than many alternatives. Even then, are you doing this operation more than … let’s say … 1 million times per second? No? Then it probably doesn’t matter, anyways.

So what matters if you do care about performance very much (hot loop, millions of operations per second), is understanding what format! does. It creates a String which involves allocation. It works with Display and Debug trait mechanism, which can have a tiny little bit of overhead. The convenience of supporting the syntax of formatting expression itself has essentially no overhead at all though, by the way; those are interpreted at compile-time.

Now you mention some usage of .push(..) and .push_str(..); this gives the tiniest of hint for your actual use-case; but not enough to fully determine if it’s comparable to – say – something like format!("{n}").len(), i.e. a use case where some of the functionality that format! offered wasn’t actually used at all.

For example, if you don’t actually need the String, in some use-cases you can often skip the need for allocation by using functionality such as format_args or the write! macro instead.

9 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.