Reputation: 1949
I have two questions:
Is two calls to std::cout less efficient than one?
If yes, does the compiler (usually) optimize it and generate equal assembly for the three cases shown below?
For example:
std::cout << "a" << "b";
or
std::cout << "ab";
or
std::cout << "a";
std::cout << "b";
I ask, because I think the last one is the most readable for a longer list of text to output.
Upvotes: 2
Views: 247
Reputation: 129374
In THIS example,
std::cout << "ab";
is more efficient (and I have not seen a compiler "merge" the output, but I must say I haven't been looking for that either - I'll go look and edit if I find something interesting).
Edit: Clang (version 3.7 as of last weekend) does not merge the string in the case of:
std::cout << "a" << "b";
The other two code snippets are identical except for number of lines and source code size [which generally has no impact on the executable, so "doesn't matter"].
As mentioned in the comments, if you actually have two strings that are for example variables, the overhead of constructing a new string is almost certainly not worth the trouble, and very rarely does the performance of std::cout
matter at all to the overall performance of the application, other than the overall I/O bandwidth limiting the execution of the application. In other words, trying to save a few microseconds when it takes several milliseconds to write something to a console is pointless.
Upvotes: 3