gpt4 book ai didi

c# - 什么限制了 C# 中的数组大小?

转载 作者:太空宇宙 更新时间:2023-11-03 19:05:15 28 4
gpt4 key购买 nike

我想创建两个 200M int 元素数组。像那样:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Arr
{
class Program
{

static void Main(string[] args)
{

int Min = 0;
int Max = 10;
int ArrSize = 200000000;

int[] test2 = new int[ArrSize];
int[] test3 = new int[ArrSize];

Console.ReadKey();

}
}
}

但是,在 VS2013 下,我遇到内存不足异常,黄色箭头指向 int[] test3 = new int[ArrSize]; 行。该机器有 12GB 的 RAM。

如果我将元素数量减少到 150M,则不会抛出异常。

如果我只初始化一个大小为 200M 的数组,则不会抛出异常。

为什么?

最佳答案

The machine has 12GB of RAM.

影响程序的速度(取决于有多少空闲),但物理内存大小对分配成功或失败没有影响。这是由可用地址空间决定的。

如果您正在编译为 32 位,尤其是如果 you are not using the /LARGEADDRESSAWARE option ,那么您将只能分配少数大对象,因为它们必须适合单个 2GB 地址空间,而该空间被 DLL 和其他分配打断。

如果您确实需要那么大的对象,最好使用 64 位。对于 32 位程序,您可以通过将对象分成更小的 block 来部分解决此问题,从而增加找到足够大的地址空间空闲区域的机会。

VS 2013 中 C# 控制台应用程序的默认设置是“AnyCPU”,以及“首选 32 位”。

您可以在“项目属性”->“构建”选项卡上更改此设置。 enter image description here

关于c# - 什么限制了 C# 中的数组大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29043166/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com