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

            Bug ID: 110801
           Summary: std::format code runs slower than equivalent {fmt}
                    code
           Product: gcc
           Version: 13.1.1
            Status: UNCONFIRMED
          Keywords: missed-optimization
          Severity: normal
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: redi at gcc dot gnu.org
  Target Milestone: ---

Using the benchmark from
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0645r10.html#Benchmarks
and adding:

#if __has_include(<format>)
#include <format>
#endif

#ifdef __cpp_lib_format
void std_format(benchmark::State& s) {
  size_t result = 0;
  while (s.KeepRunning()) {
    for (auto i: data)
      result += std::format("{}", i).size();
  }
  benchmark::DoNotOptimize(result);
}
BENCHMARK(std_format);

void std_format_to(benchmark::State& s) {
  size_t result = 0;
  while (s.KeepRunning()) {
    for (auto i: data) {
      char buffer[12];
      result += std::format_to(buffer, "{}", i) - buffer;
    }
  }
  benchmark::DoNotOptimize(result);
}
BENCHMARK(std_format_to);
#endif

I get:

Benchmark              Time             CPU   Iterations
--------------------------------------------------------
sprintf           708600 ns       706474 ns          946
ostringstream    1216025 ns      1210087 ns          589
to_string         178579 ns       178088 ns         3824
format            306344 ns       305365 ns         2345
format_to         145606 ns       145223 ns         4940
std_format        514969 ns       513563 ns         1376
std_format_to     436502 ns       435402 ns         1567

The std::to_string performance is good, but std::format is much slower than
fmt::format.

Reply via email to