StringBuilder的最大容量 [英] MaxCapacity of StringBuilder
问题描述
为什么此代码在i = 690864192上抛出OutOfMemoryException?
why does this code throw an OutOfMemoryException on i = 690864192?
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Int32.MaxValue; i++)
{
sb.Append("s");
}
Console.WriteLine(sb.ToString());
Console.Read();
默认容量为16个字符,但随着最大容量的增长而增加,最大为int.MaxValue = 2,147,483,647.那么,为什么当字符数为690,864,192(远小于最大容量)时,会引发异常吗?
The default capacity is 16 chars, but this grows at it needs to up to the max which is int.MaxValue = 2,147,483,647. So why is it when number of chars is 690,864,192 which is much less than the max capacity, does it throw an exception?
推荐答案
每次 StringBuilder
分配一个新的 char []
(通过指向先前的块
实例..这是另一个 StringBuilder
)..您正在对垃圾收集器施加巨大的压力.
Each time the StringBuilder
allocates a new char[]
(by pointing to a previous chunk
instance.. which is another StringBuilder
).. you're putting an insane amount of pressure on the garbage collector.
对对象大小有内存限制.您的对象可能会在到达末尾之前为应用程序进程分配最大的内存...因此,在任何情况下, OutOfMemoryException
.
There are memory restrictions on the size of objects. Your object will likely max out your assigned memory for your applications process before reaching the end... hence OutOfMemoryException
in either case.
您拥有的最后一个 StringBuilder
实例指向最大化前的最后一个实例.永远不会清除的GC的根.
The last StringBuilder
instance you have points to the last instance before it maxed out.. that one also points to the previous instance before it maxed out... etc. You have a gigantic graph of roots for the GC that never get cleaned up.
这篇关于StringBuilder的最大容量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!