Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does GC.GetTotalMemory() report huge memory allocations?

Tags:

c#

.net

I have been playing around with GC.GetTotalMemory(). When I create a local variable of type Titles in the example below, the consumed amount of memory increases by 6276 bytes. What's going on here?

class Program
{
    enum Titles { Mr, Ms, Mrs, Dr };

    static void Main(string[] args)
    {
        GetTotalMemory();
        Titles t = Titles.Dr;
        GetTotalMemory();
    }

    static void GetTotalMemory()
    {
        long bytes = GC.GetTotalMemory(true);
        Console.WriteLine("{0}", bytes);
    }
}
like image 319
Captain Sensible Avatar asked Apr 02 '10 11:04

Captain Sensible


1 Answers

I think it is because allocator somewhere bite a big piece of memory. It will use it for more than one object. Try to do:

GetTotalMemory();
Titles t = Titles.Dr;
GetTotalMemory();
Titles t2 = Titles.Mr;
GetTotalMemory();

and see what happens.

here is what i see, and GetTotalMemory() is not so innocent:

    GetTotalMemory();
    Titles t = Titles.Dr;            
    GetTotalMemory();

outputs:

12828
19484

and this:

GetTotalMemory();
//Titles t = Titles.Dr;            
GetTotalMemory();

outputs:

12828
19484

actually you should not pay attention to small fluctuations of free memory:

Then saith he unto them, Render therefore unto Caesar the things which are Caesar's; and unto God the things that are God's

:)

like image 98
Andrey Avatar answered Sep 20 '22 21:09

Andrey