Get List Byte Size <T>
Stupid question, but in the winforms application that I am currently working with, I would like to get the number of bytes allocated / used by List<[SomeObject]> stored in memory (for statistical purposes). Is it possible? I looked at the possible options, but obviously there is no myList.GetTotalBytes() method.
I'm not sure if the runtime provides a reliable programmatic method for getting the size of an object, however there are several options for you:
- use a tool like CLR Profiler
- use Marshal.SizeOf () (returns unmanaged object size)
- serialize your object in binary format to get closer
It really depends on what you mean. You can predict how many bytes will be used by the list itself, but this is not the same as predicting how many bytes may be eligible for garbage collection if the list has become suitable for collection.
List Bits:
- Base array (
T[]- reference to an array to which only the list will have access) - Size (int)
- Sync Root (link)
- Version Number (int)
A complex bit decides how much to count. Each of them is fairly easy to calculate (especially if you know that T is a reference type, for example), but do you want to count the objects referenced by the list? Are these links the only ones or not?
You say you want to know "for statistical purposes" - could you please clarify? If you can say that you are really interested (and a little more information about what is in the list and whether there may be other links to the same objects), we could probably help more.
This may be the right answer, but I'm going to go on a limb and say if you are doing statistical comparisons, binary-serialize the object using a MemoryStream and then view its Length property as such:
List<string> list = new List<string> { "This", "is", "a", "test" }; using (Stream stream = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, list); Console.WriteLine(stream.Length); } Please note that this may change between different versions of the framework and will be useful only for comparison between graphs of objects within the same program.