Reputation: 272
I noticed that the string capacities in C++ follow this pattern:
Here are the string capacities for strings up to length 500:
15
30
60
120
240
480
960
Capacities were found with the following C++ program:
#include <iostream>
#include <vector>
using namespace std;
string getstr(int len) {
string s = "";
for (int i=0; i<len; i++) {
s.append("1");
}
return s;
}
int main() {
vector<int> capacities;
int prevcap;
for (int i=0; i<500; i++) {
int cap = getstr(i).capacity();
if (cap > prevcap) {
capacities.push_back(cap);
prevcap = cap;
}
}
for (int i : capacities) {
cout << i << endl;
}
}
What is the logic behind choosing this algorithm? Do the numbers (here 15 and 2) have any significance, or have they been randomly chosen? Also, does this algorithm vary from compiler to compiler? (This was compiled and tested with g++ 5.4.0 on Ubuntu 16.04) Any insights are appreciated.
Upvotes: 5
Views: 426
Reputation: 87959
Doubling is a well known method. It amortizes the cost of reallocation making push_back
a constant time operation (as it is required to be). The 'obvious' alternative of adding a fixed size would make push_back
a linear time operation. Other patterns are possible though, any multiplicative increase would work theoretically, and I once read an article advocating that each increased capacity should be taken from the next term in a Fibonacci sequence.
I imagine the initial size of 15 is chosen with short string optimization (SSO) in mind. With SSO the string data is stored in the string object itself instead of in separately allocated memory. I imagine 15 is the largest short string that can be accommodated in this particular implementation. Knowing what sizeof(std::string)
is might shed some light on this.
Upvotes: 10