【发布时间】:2017-04-20 18:16:03
【问题描述】:
考虑这段代码:
string value = new string('a', int.MaxValue);
当我们运行该代码时,会发生 OutOfMemoryException。Physical memory 在 Windows 8 中的限制是 128 GB。
那么为什么 .Net 为该代码抛出 OutOfMemoryException?
此外,这段代码永远不会抛出 OutOfMemoryException :
List<string> list = new List<string>();
for (int i = 0; i < 100000000000; i++)
{
list.Add(new string('a', 100 ));
}
我在 64 位模式下运行它。
【问题讨论】:
-
当涉及到内存不足错误时,物理内存几乎是无关紧要的。您可能想阅读It's the address space, stupid
-
字符串不能超过 2^30 (1,073,741,824) 个字符,因为 Microsoft CLR(公共语言运行时)规定了 2GB 的限制。
-
小知识:那个for循环坏了,100000000000大于
int.MaxValue,需要用long来代替。
标签: c# memory-management