为什么 int 数组的最大大小低于 Int32.MaxValue? [英] Why is Max size of int array lower than Int32.MaxValue?

查看:57
本文介绍了为什么 int 数组的最大大小低于 Int32.MaxValue?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使 这篇文章说它应该可以工作,如果你创建一个大小为 Int32.MaxValue 的 int 数组,它会抛出一个 OutOfMemoryException:数组维度超出支持的范围.

Even though this post says it should work, if you create an int array of size Int32.MaxValue, it throws an OutOfMemoryException: Array dimensions exceeded supported range.

根据我的测试,数组可以初始化的最大大小似乎是 Int32.MaxValue - 1048576 (2,146,435,071).1048576 是 2^20.所以只有这样才有效:

From my testing, it seems like the maximum size that an array can be initialized to is Int32.MaxValue - 1048576 (2,146,435,071). 1048576 is 2^20. So only this works:

var maxSizeOfIntArray = Int32.MaxValue - 1048576;
var array = new int[maxSizeOfIntArray];

有人知道为什么吗?有没有办法创建更大的整数数组?

Does any one know why? Is there a way to create a larger integer array?

PS:我需要使用数组而不是列表,因为 Math.Net 库只返回密码安全伪随机数生成器随机数集的数组

PS: I need to use arrays instead of lists because of a Math.Net library that only returns arrays for sets of random numbers that are cryptographically secure pseudo random number generator

是的,我查看了链接的其他问题,但它们不正确,因为这些问题说最大的大小是 Int32.MaxValue,这与我的计算机允许我做的不同

Yes I have looked at the other questions linked but they are not correct as those questions say the largest size is Int32.MaxValue which is not the same as what my computer lets me do

是的,我知道数组的大小将是 8GB,我需要生成一个数十亿行的数据集,以便使用更难的测试套件来测试随机性

Yes, I do know the size of the array will be 8GB, I need to generate a data set of billions of rows in order to test the randomness with the die harder suite of tests

我还尝试了创建 BigArray 的选项,但这并没有似乎不再支持 C# 了.我找到了它的一个实现,但它在索引 524287 处引发了 IndexOutOfRangeException,即使我将数组大小设置为 300 万.

I also tried the option of creating a BigArray<T> but that doesn't seem to be supported in C# anymore. I found one implementation of it, but that throws an IndexOutOfRangeException at index 524287, even though I set the array size to 3 million.

推荐答案

Int32 是 32 位,或 4 个字节.Int32 的最大值是 2,147,483,647.因此,如果您可以创建一个包含 2,147,483,647 个元素的数组,其中每个元素为 4 个字节,那么您将需要一块大小为 8GB 的​​连续内存.这是非常巨大的,即使您的机器有 128GB 的​​ RAM(并且您在 64 位进程中运行),这也超出了现实的比例.如果您真的需要使用那么多内存(并且您的系统有),我建议您使用本机代码(即 C++).

An Int32 is 32 bits, or 4 bytes. The max value of an Int32 is 2,147,483,647. So, if you could create an array of 2,147,483,647 elements, where each element is 4 bytes, you would need a contiguous piece of memory that is 8GB in size. That is ridiculously huge, and even if your machine had 128GB of RAM (and you were running in a 64-bit process), that would be outside of realistic proportions. If you really need to use that much memory (and your system has it), I would recommend going to native code (i.e., C++).

这篇关于为什么 int 数组的最大大小低于 Int32.MaxValue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆