Is it memory efficient to first create string and then add it to vector through move semantics or to create element in vector?

std::vector<std::string> v;
v[0] += 's';
v[0] += 't';
v[0] += 'r';
v[1] += 's';
v[1] += 't';
v[1] += 'r';


std::vector<std::string> v;
std::string s = "";
s += 's';
s += 't';
s += 'r';
std::string s1 = s;

In first case we first create element in vector and then modify it. I suppose in such small case there will be enough memory reserved in first place, but if it's not - will be vector v contiguous in memory, or just pointers to string objects? Does adding an element to string element in a vector makes last one to perform memory reallocation?

In second case, will be memory allocated for strings used as rvalue an added directly into allocated somewhere vector without memory reallocation for strings?


std::vector always stores data in a contiguous block of memory. In both cases if the strings You want to push back can't fit in the already allocated memory, there will be reallocation.

By doing v.push_back(std::move(s)) the data will be moved to the std::string in the vector from s, so the unused copy of s's data won't remain in the memory. This can be more efficient for large amount of data, but in Your case this won't make much difference.

In the second case You also have to initialize two more strings...

Need Your Help

Backendless - How To Get Objects From 'Data'

ios objective-c xcode backendless

How do I get all the objects from Backendless's database into a UITableView in my iOS app?

Categories list pagination

cakephp cakephp-2.2

I used the following code in admin_index() method that is in CategoriesController