Determining the number of bytes used by a variable
I have the following array:
byte[][] A = new byte[256][];
Each element of this array references another array.
A[n] = new byte[256];
However, most elements reference the same array. In fact, array A only references two or three unique arrays.
Is there an easy way to d开发者_Python百科etermine how much memory the entire thing uses?
If your question is to find out the number of unique 1D arrays, you could do:
A.Distinct().Count()
This should do because equality of arrays works on reference-equality by default.
But perhaps you're looking for:
A.Distinct().Sum(oneDimArray => oneDimArray.Length) * sizeof(byte)
Of course, "number of bytes used by variables" is a somewhat imprecise term. In particular, the above expression doesn't account for the storage of the variable A
, references in the jagged array, overhead, alignment etc.
EDIT: As Rob points out, you may need to filter null
references out if the jagged-array can contain them.
You can estimate the cost of storing the references in the jagged-array with (unsafe
context):
A.Length * sizeof(IntPtr)
I don't believe there's any built in functionality.
Whipped this up very quickly, haven't tested it throughly however;
void Main()
{
byte[][] a = new byte[256][];
var someArr = new byte[256];
a[0] = someArr;
a[1] = someArr;
a[2] = new byte[256];
getSize(a).Dump();
}
private long getSize(byte[][] arr)
{
var hashSet = new HashSet<byte[]>();
var size = 0;
foreach(var innerArray in arr)
{
if(innerArray != null)
hashSet.Add(innerArray);
}
foreach (var array in hashSet)
{
size += array.Length * sizeof(byte);
}
return size;
}
I just a modified Rob's getSize method to use the Buffer helper class.
private long getSize(byte[][] arr)
{
Dictionary<byte[], bool> lookup = new Dictionary<byte[], bool>();
long size = 0;
foreach (byte[] innerArray in arr)
{
if (innerArray == null || lookup.ContainsKey(innerArray)) continue;
lookup.Add(innerArray, true);
size += Buffer.ByteLength(innerArray);
}
return size;
}
精彩评论