I am timing calls to snprintf vrs ostringstream and get an incredible result: the calls to the latter take about 32 times longer in Visual Studio 2015 Update 3!!
Probably because you're creating new instances of those two variables 1,000,000 times in your loop for the ostringstream, but you never create any variables in that sprintf() loop. Also why are you using setw() in the ostringstream version but not using the width modifier in your sprintf() loop?
Also it would be helpful if you showed the actual output from your "program".
146401311 nanoseconds for snprintf
74096553 nanoseconds for ostringstream
but (on my desktop) vs 2015:
136668209 nanoseconds for snprintf
450268399 nanoseconds for ostringstream
It could be instructive to follow through with a profiler to see what the differences are. Microsoft implementation of streams is known to have some major flaws, but the ones I know about shouldn't apply here.
646658137 nanoseconds for snprintf
14283754345 nanoseconds for ostringstream
relation: 22.0886
Yes, you are right on the fact that we are constructing and destructing a million objects in the second loop. However my concern is why the C++ standard eliminated strstream which could use an existing buffer and left only a C function for us to use?? That's why I find a ratio of about 22 in execution time to be way unacceptable.
Is there a way to reuse the ostringstream in the loop?