为什么我无法在 .NET 中创建大小超过 2GB 的对象,即使在 x64 上也是如此?
阅读 C# 字符串(以及其他.NET API)的大小限制为 2GB? 我在 .NET 3.5 中尝试过大字符串和数组。我发现我可以分配的最大数组是 int.MaxValue - 56 字节。字符串也有类似的情况:我能得到的最大字符是 (int.MaxValue - 58) / 2
个字符(因为每个字符占用 2 个字节)。之后它会抛出OutOfMemoryException
。
为什么存在这种限制?我在实践中并没有遇到过这种情况 - 我只是对 .NET 的内部工作原理感到好奇。
是的,当然,这是在具有充足 RAM 的 64 位计算机上 - 是的,该进程作为 64 位进程运行。 (我实际上可以分配 3 个这样的数组或字符串,总内存使用量为 6GB。)
After reading Are C# Strings (and other .NET API’s) limited to 2GB in size? I played around with large strings and arrays in .NET 3.5. I found that the largest array I could allocate was int.MaxValue - 56
bytes. Similar thing for strings: the largest I could get was (int.MaxValue - 58) / 2
characters (since each character took 2 bytes). After that it throws OutOfMemoryException
.
Why does this limitation exist? Not that I've ever run into it in practice - I'm just curious about the inner workings of .NET.
Yes, this was on a 64-bit machine with plenty of RAM, of course - and yes, the process was running as a 64-bit process. (I could actually allocate 3 such arrays or strings for a total memory usage of 6GB.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 4.5 之前的 .NET 版本中,最大对象大小为 2GB。从 4.5 开始,您可以分配更大的对象,如果 gcAllowVeryLargeObjects< /a> 已启用。请注意,
string
的限制不受影响,但“数组”也应该覆盖“列表”,因为列表由数组支持。In versions of .NET prior to 4.5, the maximum object size is 2GB. From 4.5 onwards you can allocate larger objects if gcAllowVeryLargeObjects is enabled. Note that the limit for
string
is not affected, but "arrays" should cover "lists" too, since lists are backed by arrays.这是一项设计决策,将 GC 堆上的对象大小限制为 2GB,即使在 x64 上也是如此。参与设计决策的人员之一在此发表了一篇不错的博客文章:
链接
It was a design decition to restrict the size of an object on the GC Heap to 2GB, even on x64. Good blog post on it here from one of those involved in the design decision:
Link