Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is snprintf faster than ostringstream or is it?

Tags:

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

like image 679
kal Avatar asked Jan 15 '09 01:01

kal


2 Answers

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 protected 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.

like image 148
Max Lybbert Avatar answered Oct 25 '22 15:10

Max Lybbert


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.

like image 31
user52875 Avatar answered Oct 25 '22 17:10

user52875