I read somewhere that snprintf is faster than ostringstream. Has anyone has any experiences with it? If yes why is it faster.
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.
We replaced some stringstreams in inner loops with sprintf (using statically allocated buffers), and this made a big difference, both in msvc and gcc. I imagine that the dynamic memory management of this code:
{ char buf[100]; int i = 100; sprintf(buf, "%d", i); // do something with buf }
is much simpler than
{ std::stringstream ss; int i = 100; ss << i; std::string s = ss.str(); // do something with s }
but i am very happy with the overall performance of stringstreams.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With