Output speed

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 have run both of them many times to find that the second is faster. I spent some time trying to figure out why. I think this is because in the first, the string is first concatenated and then displayed. But the second displays directly on the screen. It is right?

+4
source share
4 answers

The first one will probably include several memory allocations for string concatenations, and then copying the final concatenated string to the output buffer. The second will simply copy the already selected string data into the already allocated output buffer.

+4
source

From a theoretical point of view, the second example is linear time, and the first may be quadratic time (among the substrings), depending on the implementation.

To determine if this will be the case with your implementation, you will have to look at the source code and (because the compiler can optimize the subject) machine code.

In short, the reasons that depend on the implementation, and in general, to determine the "fastest", you have no choice but MEASURE . Causes can act as heuristic recommendations. But that’s it: in the end it measures reality, which matters.

0
source

Your hypothesis that the second is faster due to the first creation of string objects is most likely true. The key here is "likely." These are std library functions and, as such, may have different implementation details, since the standard defines behavior, and not how it is implemented. Theoretically, you can find a standard library implementation where the true opposite of your results is.

0
source

I think you want to take a look at this answer from a previous question for a complete entry: Efficient string concatenation in C ++

0
source

Source: https://habr.com/ru/post/1445676/


All Articles