Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

memory

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?

Thanks

like image 736
jheppinstall Avatar asked Dec 05 '22 07:12

jheppinstall


2 Answers

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...

like image 132
Marc Gravell Avatar answered Dec 07 '22 21:12

Marc Gravell


In order to ensure you have enough free memory you could use a MemoryFailPoint. If the memory cannot be allocated, then an InsufficientMemoryException will be generated, which you can catch and deal with in an appropriate way.

like image 45
David Kirkland Avatar answered Dec 07 '22 19:12

David Kirkland