Why is snprintf faster than ostringstream or is it?

c, c++, performance

Solution

`std::ostringstream` is not required to be slower, but it is generally slower when implemented. FastFormat's website has some benchmarks.

The Standard library design for streams supports much more than `snprintf` does. The design is meant to be extensible, and includes `protected` `virtual` methods that are called by the publicly exposed methods. This allows you to derive from one of the stream classes, with the assurance that if you overload the `protect`ed method you will get the behavior you want. I believe that a compiler could avoid the overhead of the `virtual` function call, but I'm not aware of any compilers that do.

Additionally, stream operations often use growable buffers internally; which implies relatively slow memory allocations.

Problem

I read somewhere that snprintf is faster than ostringstream. Has anyone has any experiences with it? If yes why is it faster.

Original source