Std :: string capacity size

Is row capacity size always a multiple of 15?

for example: in all cases, the capacity is 15

string s1 = "Hello"; string s2 = "Hi"; string s3 = "Hey"; 

or is he random?

+4
source share
3 answers

Is row capacity size always a multiple of 15?

No; the only guarantee about std::string 's capacity is that s.capacity() >= s.size() .

A good implementation is likely to increase capacity exponentially, so that it doubles in size each time a redistribution of the underlying array is required. This is necessary for std::vector , so push_back can have amortized constant time complexity, but there is no such requirement for std::string .

In addition, the std::string implementation can perform small string optimizations, where strings smaller than a certain number of characters are stored in the std::string object itself, and not in a dynamically allocated array. This is useful because many lines are short, and dynamic allocation can be expensive. Typically, a small row optimization is performed if the number of bytes needed to store the string is less than the number of bytes needed to store the pointers in a dynamically allocated buffer.

Regardless of whether your particular implementation performs small string optimizations, I don't know.

+8
source

Implementation specificity - std :: String usually selects a small start line, usually 16 bytes are used. This is a trade-off between having to reuse and moving for very short lines and without losing space.

+4
source

This is an implementation detail that you should not rely on; to see exactly how std::string grows in your implementation, you can take a look at the sources of your CRT. In the general case, it has exponential growth.

0
source

Source: https://habr.com/ru/post/1340209/


All Articles