https://gcc.gnu.org/bugzilla/show_bug.cgi?id=110801

--- Comment #1 from Jonathan Wakely <redi at gcc dot gnu.org> ---
Created attachment 55739
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=55739&action=edit
Add special case for format("{}", integer)

With this patch std::format is much closer to fmt::format:

Benchmark              Time             CPU   Iterations
--------------------------------------------------------
sprintf           554621 ns       553889 ns         1241
ostringstream     932465 ns       931258 ns          746
to_string         122602 ns       122425 ns         5424
format            241978 ns       241656 ns         2939
format_to         109541 ns       109391 ns         6282
std_format        282151 ns       281787 ns         2490
std_format_to     225596 ns       225301 ns         3080

std::format_to could still be faster. It should be potentially as fast as
to_string.

The patch is just a prototype that only optimizes for integers, but the idea
could be extended to other types too. For integers, floats, strings, and
pointers we can skip the formatter::parse and formatter::format calls for a
"{}" format string and just do the basic output form, with none of the
additional code for alternative presentation forms, alignment, width, precision
etc.

As well as short-circuiting most of the formatting logic, the other part of the
optimization is writing directly to the output buffer if it is a contiguous
iterator (or a sink iterator that writes to a contiguous container). This is
more efficient than writing to a buffer and then copying to the output.  This
could be extended to work with a back_insert_iterator<string> or
back_insert_iterator<vector>, as we could extract the container, resize it, and
then write directly into it.

Reply via email to