I want to make an array of size 10^9 elements where each elements can be an integer of the same size. I always get an OutOfMemoryException at the initialization line. How can I achieve this?
If this is not possible, please suggest alternative strategies?
Assuming you mean
intas the element type, you can do this using .NET 4.5, if you’re using a 64-bit CLR.You need to use the
<gcAllowVeryLargeObjects>configuration setting. This is not on by default.If you’re using an older CLR or you’re on a 32-bit machine, you’re out of luck. Of course, if you’re on a 64-bit machine but just an old version of the CLR, you could encapsulate your “one large array” into a separate object which has a list of smaller arrays… you could even implement
IList<int>that way so that most code wouldn’t need to know that you weren’t really using a single array.(As noted in comments, you’ll still only be able to create an array with 231 elements; but your requirement of 109 is well within this.)