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