user44322
user44322

Reputation: 361

Speed of output

I am coding in C++. Let s be some string. I am asked to determine which of the following is faster:

cout << "s:"  + s  + "s:"  + s  + " s:"  + s  + "\n";

cout << "s:" << s << "s:" << s << " s:" << s << "\n";

I ran both of them repeatedly to find that the second one is faster. I spent a while trying to figure out why. I think it is because in the first one, the string is first concatenated then output to the screen. But the second one just output straight to the screen. Is that correct?

Upvotes: 4

Views: 151

Answers (4)

Michael
Michael

Reputation: 10474

I think you want to take a look at this answer from a previous question for a full write-up: Efficient string concatenation in C++

Upvotes: 0

RC.
RC.

Reputation: 28267

Your hypothesis that the second is faster due to the first creating string objects is likely correct. The key here is "likely". These are std library functions and as such can have different implementation details as the standard defines behavior and not how it is implemented. In theory, you could find a standard library implementation where the opposite of your findings is true.

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

The first will likely involve a few memory allocations for the string concatenations, followed by the copying of the final concatenated string to the output buffer. The second one will simply copy already allocated string data to an already allocated output buffer.

Upvotes: 4

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145429

From a theoretical perspective the second example is linear time while the first one can be quadratic time (in the number of substrings), depending on the implementation.

To determine whether that is the case with your implementation, you will have to look at the source code and (because the compiler might optimize thing) at the machine code.

In short, the reasons why depend on the implementation, and in general, to determine "which is fastest", you have no option but to MEASURE. The "reasons why" can act as heuristic guidelines. But that's all: in the end it's measurements, reality, that counts.

Upvotes: 0

Related Questions