-3

How to get the allocated space in memory for array A with N rows and M columns in C# ?

is there any function or something like this ?

I search several times in internet; but i can't find any good answer for my question that i understand that.

Death Programmer
  • 896
  • 2
  • 11
  • 28

2 Answers2

2

If you want to know that how much memory a two dimensional array will consume, then it will depend on the data type.

e.g. if you have an array of 3 rows and 4 columns with type int then as an int consumes 32 bit or 4 bytes. So whole array will consume 32*3*4 = 384 bits or 4*4*3 = 48 bytes.

For simple calculation you can use following code for getting the memory consumption by different value types:

var size = BitConverter.GetBytes(value).Length; // here value can be any value type.
Nitin Joshi
  • 1,638
  • 1
  • 14
  • 17
2

You can't know the exact size occupied in memory by the entire array with all mem-paddings and etc. You can use the following approach to estimate of how many bytes in memory occupied by all array cells.:

long size1 = GetArrayElementsSizeInMemory(new int[] { 1, 2 }); // 8 bytes
long size2 = GetArrayElementsSizeInMemory(new int[,] { { 1 }, { 2 }, { 3 } }); // 12 bytes
long size3 = GetArrayElementsSizeInMemory(new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } }); // 16 bytes
//...
static long GetArrayElementsSizeInMemory(Array array) {
    return array.Length * GetArrayElementSize(array);
}
static long GetArrayElementSize(Array array) {
    var elemenType = array.GetType().GetElementType();
    return elemenType.IsValueType ? Marshal.SizeOf(elemenType) : IntPtr.Size;
}
Community
  • 1
  • 1
DmitryG
  • 17,677
  • 1
  • 30
  • 53