StringBuilder如何决定它的容量应该有多大?
我知道当 sb 已满时使用 sb.Append(..) 时,StringBuilder 对象会分配更多内存。但容量会增加多少呢?
StringBuilder sb = new StringBuilder(5);
sb.Append("0123456789");
现在某人的能力是多少,为什么?什么是乘数?
只是为了清楚起见。我问的是容量而不是长度。
谢谢!
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");
Now what is the capacity of sb and why? What is the multiplier?
Just for clarity. I am asking about capacity and not length.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除某些特殊情况外,容量每次都会加倍:
您可以使用.NET Reflector或下载参考源来查看该算法。
我无法发布官方 .NET 实现的源代码,但这里是 Mono 实现的代码:
我还建议您不要编写依赖于此特定算法的代码,因为它是实现细节,而不是其他东西这是由接口保证的。
The capacity doubles each time apart from some special cases:
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:
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.
它呈指数增长(具体来说,每次重新分配都会加倍),以便允许一系列追加花费 O(N) 时间而不是 O(N²) 时间。
It's exponential growth (specifically, doubling with each reallocation), in order to allow a series of appends to take O(N) time instead of O(N²) time.