Reputation: 1072
I have to construct a string by concatenating a few other strings. I also know the maximum size of the string, and I want to reserve the capacity so there are no reallocations. My code right now looks something like this:
#include <string>
using std::string;
// Setup
...
string a,b,c;
// Strings are filled with relevant data
...
string msg;
msg.reserve(200);
msg = "A="; msg += a; msg += ',';
msg += "B="; msg += b; msg += ',';
msg += "C="; msg += c; msg += '.';
I previously used stringstream
for this, but performance was twice as slow.
Is there a way to reserve the string capacity at construction, instead of having to allocate memory twice? Also is there a better (faster) way of appending the strings?
Upvotes: 1
Views: 113
Reputation: 385098
Is there a way to reserve the string capacity at construction instead of having to allocate memory twice?
There is no "allocating memory twice" here. You correctly create a string then ask it to reserve some memory. Other than reserving a more accurate amount (rather than just guessing 200
), you're fine.
Technically, an implementation is allowed to start off with an unspecified capacity, but it's likely that you're seeing the results of small-string optimisation (a statically-allocated buffer inside the std::string
itself, to avoid dynamic allocations in some cases) rather than this feature being used.
If you're really concerned about it, you could instantiate the string with 200 \0
characters, then erase them all; then its underlying capacity will be consistent.
Upvotes: 2