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