Get byte size of List<T>
Silly question, but in a winforms app Im currently working on, I would like to get the amount of bytes allocated/used by a List<[Som开发者_C百科eObject]>
held in memory (for statistical purposes). Is this possible? I have searched thru the possible options, but there is obviously no myList.GetTotalBytes()
method.
It really depends on what you mean. You can predict how many bytes will be used by the list itself - but that's not the same as predicting how many bytes might be eligible for garbage collection if the list became eligible for collection.
Bits of the list:
- The backing array (
T[]
- a reference to an array that only the list will have access to) - The size (int)
- A sync root (reference)
- The version number (int)
The tricky bit is deciding how much to count. Each of those is fairly easy to calculate (particularly if you know that T is a reference type, for example) but do you want to count the objects referenced by the list? Are those references the only ones, or not?
You say you want to know "for statistical purposes" - could you be more precise? If you can say what you're really interested in (and a bit more information about what's in the list and whether there may be other references to the same objects) we could probably help more.
This may be a full-of-horse-pucky answer, but I'm going to go out on a limb and say if you're doing statistical comparisons, do a binary serialize of the object to a MemoryStream
and then look at 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);
}
Take note that this could change between different versions of the framework and would only be useful for comparisons between object graphs within a single program.
I'm not sure the runtime provides a reliable programmatic method of getting an object's size, however there are some options open to you:
- use a tool like CLR Profiler
- use Marshal.SizeOf() (returns the unmanaged size of the object)
- serialize your object to binary for an approximation
精彩评论