The capacity doubles each time apart from some special cases:
- If doubling is not enough then the capacity is further increased to the exact amount that is required.
- There is an upper limit - 0x7fffffff.
You can see the algorithm by using .NET Reflector or downloading the reference source.
I can't post the source code for the official .NET implementation but here's the code for the Mono implementation:
// Try double buffer, if that doesn't work, set the length as capacity
if (size > capacity) {
// The first time a string is appended, we just set _cached_str
// and _str to it. This allows us to do some optimizations.
// Below, we take this into account.
if ((object) _cached_str == (object) _str && capacity < constDefaultCapacity)
capacity = constDefaultCapacity;
capacity = capacity << 1; // This means "capacity *= 2;"
if (size > capacity)
capacity = size;
if (capacity >= Int32.MaxValue || capacity < 0)
capacity = Int32.MaxValue;
if (capacity > _maxCapacity && size <= _maxCapacity)
capacity = _maxCapacity;
}
I would also recommend that you don't write code that relies on this specific algorithm as it is an implementation detail, and not something that is guaranteed by the interface.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…