This question already has an answer here:
- Find size of object instance in bytes in c# 13 answers
I need to know how much bytes my object consumes in memory (in C#). for example how much my Hashtable
, or SortedList
, or List<String>
.
This question already has an answer here:
I need to know how much bytes my object consumes in memory (in C#). for example how much my Hashtable
, or SortedList
, or List<String>
.
In debug mode
load SOS
and execute dumpheap command.
Unmanaged object:
Marshal.SizeOf(object yourObj);
Value Types:
sizeof(object val)
Managed object:
The following code fragment should return the size in bytes of any object passed to it, so long as it can be serialized. I got this from a colleague at Quixant to resolve a problem of writing to SRAM on a gaming platform. Hope it helps out. Credit and thanks to Carlo Vittuci.
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.
See Find out how much memory is being used by an object in C#? for a similar question.
this may not be accurate but its close enough for me
OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.
First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?
I had previously touched this subject in this article: