3

I am trying to populate a vector of string type and the memory for the strings will be updated periodically.I found out in a forum that, both of these processes consume a lot of time due to memory reallocation every time I update the size and I also read that the reserve function solves the problem pretty much for both the cases. -> String & vector

My vector wont need more than 1024 slots and each string will need 10 character spaces. I have reserved 1024 memory slots for my vector.

vector<string> power_set;
power_set.reserve(1024);

But is there any way to reserve the memory-slots for the strings that are inside the vector slots as well?

Thanks In Advance.

JFMR
  • 23,265
  • 4
  • 52
  • 76
Akib Sadmanee
  • 159
  • 1
  • 12
  • 1
    There's a `reserve()` function for strings. So yes, you can iterate through the container and reserve enough space for each string. – Francisco Gallego Salido Nov 30 '17 at 10:51
  • 1
    Did you consider using `std::array` instead of `std::string`? – JFMR Nov 30 '17 at 10:51
  • 5
    You actually might not need to call reserve on the string for 10 characters, because small string optimization does avoid the allocation. – Timbo Nov 30 '17 at 10:52
  • Perhaps you shouldn't believe everything you read on a forum? `string` and `vector` doesn't reallocate memory *every time* you change the size. The reallocation happens infrequently enough to make it [amortized constant time](https://stackoverflow.com/questions/200384/constant-amortized-time). Also, 1024 is a number small enough that you will hardly ever notice any difference. – Bo Persson Nov 30 '17 at 13:59
  • That makes sense @BoPersson .. thanks for the info .. then I guess I'm good to go without a reserve() function – Akib Sadmanee Nov 30 '17 at 14:05

3 Answers3

3

My vector wont need more than 1024 slots and each string will need 10 character spaces.

Then, consider the following (partial) definition of MyString class:

#include <array>
#include <string>   

class MyString {
    std::array<std::string::value_type, 10> str;

public:
// ...
};

By using MyString instead of std::string, when calling reserve on std::vector, the memory needed for the string contained in MyString (i.e.: str, which is a std::array) will be allocated:

vector<MyString> power_set;
power_set.reserve(1024);
JFMR
  • 23,265
  • 4
  • 52
  • 76
0

You can also use reserve for strings. I'm not that experienced with vectors but you could make a custom class that allocates a certain numbers of characters for a string field and make of vector of that class instead.

Megid
  • 105
  • 12
0

I would create a custom allocator which would return an extra 10 bytes whenever asked - to ensure that only 1 allocation is done / string. But I have to say this sounds a lot like premature optimisation.

UKMonkey
  • 6,941
  • 3
  • 21
  • 30