I need to know how much bytes my object consumes in memory (in C#). for example how much my hashtable, or SortedList, or List.
You can try the Marshal.SizeOf method and sizeof keyword.
Not sure if they'll work on HashTables etc, but give it a go...it may work.
Unmanaged object:
- Marshal.SizeOf(object yourObj);
Value Types:
- sizeof(object val)
Managed object:
- Looks like there is no direct way to get for managed objects, Ref:
http://blogs.msdn.com/cbrumme/archive/2003/04/15/51326.aspx
I don't think you can get it directly, but there are a few ways to find it indirectly.
One way is to use the GC.GetTotalMemory method to measure the amount of memory used before and after creating your object. This won't be perfect, but as long as you control the rest of the application you may get the information you are interested in.
Apart from that you can use a profiler to get the information or you could use the profiling api to get the information in code. But that won't be easy to use I think.
Any container is a relatively small object that holds a reference to some data storage (usually an array) outside the actual container object - and that in turn holds references to the actual objects you added to the container.
So the question how much memory a List takes is not even well defined - the size of the list object itself, memory allocated by the list object, total size for everything in the list and the amount of memory that will be freed when the list is collected are all different values.
this may not be accurate but its close enough for me
long size = 0;
object o = new object();
using (Stream s = new MemoryStream()) {
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(s, o);
size = s.Length;
}