WITH#/. NET: dictionary memory usage

I have a general dictionary that contains a bunch of data. I would like to start deleting elements (I know how to determine which ones) when the size of the dictionary starts to take up too much memory.

What is the best way for my program to control the RAM used by this dictionary?

Each element in the dictionary is a variable size.

+4
source share
3 answers

Design the size of each element and multiply it by Dictionary.Count

One way is shown here :

An exemplary method for determining the size of an object's use in memory can be performed by checking the total memory before and after creating the object. In the following example, it is assumed that you have a class named foo.

 long StopBytes = 0; foo myFoo; long StartBytes = System.GC.GetTotalMemory(true); myFoo = new foo(); StopBytes = System.GC.GetTotalMemory(true); GC.KeepAlive(myFoo); // This ensures a reference to object keeps object in memory MessageBox.Show("Size is " + ((long)(StopBytes - StartBytes)).ToString()); 

C # has a sizeof operator, which works the same as in C / C ++, but returns the size that a field of this type will have. Thus, for reference types (class, not struct), it will always return the size of the pointer (4 on 32-bit systems). Use System.Runtime.InteropServices.Marshal.SizeOf() instead.

+5
source

I do not believe that there is any API that will give you the true size of an object, but it can be determined by measuring the amount of memory used before and after creating the object; however, it is not very thread safe.

You can use System.Runtime.InteropServices.Marshal.SizeOf (), although this will not give you the exact size, it will give you the exact comparison point so that you can say something like: if the size of the object increases by X%, then delete Y amount of elements.

In addition, you can try to save the total quantity, but if the items in the collection are editable, you will need to make sure that every addition, deletion and editing is included in the calculation. You still have the problem of correctly measuring the elements you add and remove, and, as stated above, I don't believe there is an API that will do this for sure.

+1
source

When you add something to the dictionary, calculate the size of the item to be added and save the sum of each added item as a single int value, when you delete an item from the dictionary, reduce this value.

-1
source

All Articles