Jan Swart
Jan Swart

Reputation: 7221

Can std::string capacity be changed for optimisation?

Can the std::string capacity be changed to optimise it?

For example:

std::string name0 = "ABCDEABCDEABCDEF";
int cap = name0.capacity();  //cap = 31
int size = name0.size();     //size = 16

Okay, this is perfectly fine for a couple of strings in memory, but what if there are thousands? This wastes a lot of memory. Isn't it then better to use char* so you can control how much memory is allocated for the specific string?

(I know some people will ask why are there thousands of strings in memory, but I would like to stick to my question of asking if the string capacity can be optimised?)

Upvotes: 1

Views: 198

Answers (1)

Praetorian
Praetorian

Reputation: 109089

If you're asking how to reduce capacity() so that it matches size(), then C++11 added shrink_to_fit() for this purpose, but be aware that it is a non-binding request, so implementations are allowed to ignore it.

name0.shrink_to_fit();

Or there's the trick of creating a temporary string and swapping:

std::string(name0.begin(), name0.end()).swap(name0);

However, neither of these are guaranteed to give you a capacity() that matches size(). From GotW #54:

Some implementations may choose to round up the capacity slightly to their next larger internal "chunk size," with the result that the capacity actually ends up being slightly larger than the size.

Upvotes: 4

Related Questions