C++ – Alternate string formatting options in C++

cstrings

I'm looking at optimizing some string formatting code that's hit a lot in our code. We had been using ostringstream, and I converted the code to use sprintf (actually Microsoft's more secure sprintf_s). I've traded type safety for run-time performance. But I've debugged enough sprintf related weird crashes to know that sprintf has its own serious flaws that the compile time checking of ostringstream catch. But ostringstream is more than an order-of-magnitude slower then sprintf by my measure, and that's not tolerable in this code. I'm also not thrilled with the readability of C++ stream string formatting, but this may be entirely subjective.

So unfortunately when formatting strings in C++ I've got several "standard" options that are suboptimal:

  1. sprintf — fast, but not type safe. Can have insidious bugs when the wrong format string is not used.
  2. ostringstream — slow, but type safe. IMO Ugly, too verbose, and difficult to read.
  3. boost::format — a little more readable then ostringstream IMO, but in my performance benchmarks appears to be even slower then ostringstream, so this is out.

To summarize, I'm not really satisfied with the "standard" options. I'd like something that takes both performance and type safety seriously. What other string formatting options are out there for C++?

Best Answer

I recommend this formatting library which I wrote recently. Here is an incomplete list of its features:

  • Format string syntax similar to the one used by str.format in Python.
  • Type safety and support for user-defined types.
  • High speed: performance of the current implementation is close to that of glibc's (s)printf and better than performance of IOStreams. See Speed tests.

It's a new library, but it already supports almost all of the formatting options of printf (with different syntax), in addition to that it supports positional arguments, center alignment, custom fill character and user-defined types.

Update: now it also provides a safe printf implementation