I am aware about the + operator to join 2 std::string objects. And this method to join multiple strings. But I am wondering about the performance. This answer tells why + operator is inefficient as compared to a method (in Python). Is there a similar function to join multiple strings in C++ standard library?
There is no performance difference between an operator overload and method call -- depending on the calling context. At the point you should be concerned about this, you're micro optimizing.
Here's an abstract example demonstrating the concept.
class MyString
{
public:
// assume this class is implemented
std::string operator+(const std::string &rhs) const
{
return concatenate(rhs);
}
std::string concatenate(const std::string &rhs) const
{
// some implementation
}
};
MyString str1, str2;
// we can use the operator overload
std::string option1 = str1 + str2;
// or we can call a method
std::string option2 = str1.concatenate(str2);
Operator overloads exist (for the most part) to avoid typing out lengthy method calls like the latter example. It makes code more clean and concise.
If you were specifically talking about the performance of more than 2 strings, this is a different scenario. It's more performant to batch objects into one method call, as it avoids constructing more temporary objects than necessary. You won't be able to do this without a new data structure to do the heavy lifting for you.
Using the class above, we'll look at concatenating a bunch of objects together using the + operator in one expression.
std::string bigConcatenation = str1 + str2 + str1 + str2 + str1;
Firstly, you probably wouldn't be doing this if you were concerned about performance in the first place. That said, here's a pretty decent approximation of what would be happening (assuming no optimizations done by the compiler).
std::string bigConcatenation = str1;
bigConcatenation = bigConcatenation + str2;
bigConcatenation = bigConcatenation + str1;
bigConcatenation = bigConcatenation + str2;
bigConcatenation = bigConcatenation + str1;
The reason why this is not ideal, is each assignment creates a temporary object, adds them together, then assigns the result back to bigConcatenation.
Without using any extra containers, according to this answer, the most performant way of doing this would be something like this (hint: no temporaries are created in the process).
std::string bigConcatenation = str1;
bigConcatenation += str2;
bigConcatenation += str1;
bigConcatenation += str2;
bigConcatenation += str1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With