Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 determine how much memory the entire thing uses?

like image 620
Jonathan Wood Avatar asked Feb 02 '11 07:02

Jonathan Wood


2 Answers

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) 
like image 73
Ani Avatar answered Oct 20 '22 23:10

Ani


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;
}
like image 39
Rob Avatar answered Oct 20 '22 22:10

Rob