uniquenamehere
uniquenamehere

Reputation: 1949

Are two calls to cout less efficient than one?

I have two questions:

  1. Is two calls to std::cout less efficient than one?

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

Answers (1)

Mats Petersson
Mats Petersson

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

Related Questions