I\'m timing the difference between various ways to print text to standard output. I\'m testing cout
, printf
, and ostringstream
using both
std::endl
triggers a flush of the stream, which slows down printing a lot. See http://en.cppreference.com/w/cpp/io/manip/endl
It is often recommended to not use std::endl
unless you really want the stream to be flushed. If this is really important to you, depends on your use case.
Regarding why flush
has a performance impact even on a ostringstream (where no flushing should happen): It seems that an implementation is required to at least construct the sentry objects. Those need to check good
and tie
of the ostream
. The call to pubsync
should be able to be optimized out. This is based on my reading of libcpp and libstdc++.
After some more reading the interesting question seems to be this: Is an implementation of basic_ostringstream::flush
really required to construct the sentry object? If not, this seems like a "quality of implementation" issues to me. But I actually think it needs to because even a basic_stringbug
can change to have its badbit
set.