constructing a stream object is a significantly more complex operation than constructing a string object, because it has to hold (and, therefore, construct) its std::locale
member, among other things needed to maintain state (but the locale is by a large margin the heaviest).
Appending is similar: both maintain a contiguous array of characters, both allocate more when the capacity is exceeded. The only differences I can think of is that when appending to a stream, there is one virtual member function call per overflow (in addition to memory allocation/copying, which dominates overflow handling anyway), and operator<<
has to do some extra checks of the stream state.
Also, note that you're calling str(), which copies the entire string one more time, so based on what your code is written to do, the stream example does more and should be slower.
Let's test:
#include <sstream>
#include <string>
#include <numeric>
volatile unsigned int sink;
std::string contentType(50, ' ');
std::string charset(50, ' ');
int main()
{
for(long n = 0; n < 10000000; ++n)
{
#ifdef TEST_STREAM
std::ostringstream os;
os << "Content-Type: " << contentType << ";charset=" << charset << "
";
std::string header = os.str();
#endif
#ifdef TEST_STRING
std::string header("Content-Type: ");
header.append(contentType);
header.append(";charset=");
header.append(charset);
header.append("
");
#endif
sink += std::accumulate(header.begin(), header.end(), 0);
}
}
that's 10 million repetitions
On my Linux, I get
stream string
g++ 4.8 7.9 seconds 4.4 seconds
clang++/libc++ 11.3 seconds 3.3 seconds
so, for this use case, in these two implementations, strings appear to work faster, but obviously both ways have a lot to improve (reserve() the string, move stream construction out of the loop, use a stream that doesn't require copying to access its buffer, etc)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…