Do C++ formatting libraries generally fall back to *sprintf for numeric formatting?

389 Views Asked by At

I am wondering whether "all" C++ formatting libraries eventually fall back to a *sprintf function to format numbers.

I am asking this because:

  • Looking at the iostreams library that comes with Visual C++, I can see that numbers input into a stream will eventuall be formatted with sprintf_s.
  • Boost.Format just uses the available iostreams library as far as I can tell.
  • FastFormat eventually uses vsprintf to format a number.

So, are there iostreams implementations that do not use *sprintf and do the formatting themselves? Are there other formatting libraries that do not forward formatting of numbers to *sprintf family of functions?

I would appreciate answers in the form of:

  • No: implementation XY uses ABC to format numbers
  • Yes: all other (e.g. iostreams) implementations I know (X, Y, Z) also forward number formatting to stdio, because ...

Please avoid overly speculative answers.

2

There are 2 best solutions below

0
On BEST ANSWER

Boost Spirit doesn't use *printf, as can be seen from the code (real.hpp and int.hpp) and the benchmarks for e.g. ints and doubles.

The benchmark pits Boost Spirit Karma's generators against Boost.Format against sprintf and std::stringstream. Only for gcc compilers does the performance of sprintf come close in that benchmark. Otherwise, Boost Spirit is the clear winner.

enter image description here

4
On

No, for example the {fmt} library has its own implementation of integer and floating-point formatting which is much faster than common implementations of sprintf. These are the results of a double to string formatting benchmark (dtoa-benchmark) on one platform:

benchmark results

As you can see {fmt} is ~20x faster than sprintf here.

Integer formatting is also faster but not as dramatically (up to 6-7x on Linux and macOS):

enter image description here

Disclaimer: I'm the author of {fmt}.