Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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<[SomeObject]> held in memory (for statistical purposes). Is this possible? I have searched thru the possible options, but there is obviously no myList.GetTotalBytes() method.

like image 625
Shalan Avatar asked Nov 29 '09 22:11

Shalan


1 Answers

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.

like image 180
Jesse C. Slicer Avatar answered Sep 28 '22 08:09

Jesse C. Slicer