StringBuilder如何决定其容量应为多少? [英] How does the StringBuilder decide how large its capacity should be?
问题描述
我知道,当sb已满时,当您使用sb.Append(..)时,StringBuilder对象会分配更多的内存。但是该容量增加了多少?
I know that the StringBuilder object allocates more memory when you use sb.Append(..) when the sb is already at capacity. But how much does that capacity increase?
StringBuilder sb = new StringBuilder(5);
sb.Append("0123456789");
现在sb的容量是什么,为什么?什么是乘数?
Now what is the capacity of sb and why? What is the multiplier?
为清楚起见。我问的是容量而不是长度。
Just for clarity. I am asking about capacity and not length.
谢谢!
推荐答案
除某些特殊情况外,每次容量都会翻倍:
The capacity doubles each time apart from some special cases:
- 如果加倍不够,那么容量会进一步增加到确切的数量是必需的。
- 有一个上限-0x7fffffff。
您可以看到该算法通过使用.NET Reflector或下载参考源。
You can see the algorithm by using .NET Reflector or downloading the reference source.
我无法发布官方.NET实现的源代码,但这是Mono实现的代码:
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.
这篇关于StringBuilder如何决定其容量应为多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!