C# – Finding how much memory I can allocate for an array in C#


I am doing some calculations that require a large array to be initialized. The maximum size of the array determines the maximum size of the problem I can solve.

Is there a way to programmatically determine how much memory is available for say, the biggest array of bytes possible?


Best Solution

Well, relying on a single huge array has a range of associated issues - memory fragmentation, contiguous blocks, the limit on the maximum object size, etc. If you need a lot of data, I would recommend creating a class that simulates a large array using lots of smaller (but still large) arrays, each of fixed size - i.e. the indexer divides to to find the appropriate array, then uses % to get the offset inside that array.

You might also want to ensure you are on a 64-bit OS, with lots of memory. This will give you the maximum available head-room.

Depending on the scenario, more sophisticated algorithms such as sparse arrays, eta-vectors, etc might be of use to maximise what you can do. You might be amazed what people could do years ago with limited memory, and just a tape spinning backwards and forwards...