Alex
Alex

Reputation: 65

C# Garbage Collection Collect

So I was playing around with the C# Garbage Collection and I noticed a really weird thing.

Random r = new Random();
byte inl = 0;
while(true)
{
    inl = (byte)r.Next(0, 255);
    Console.WriteLine(inl);
    GC.Collect(0, GCCollectionMode.Forced, false, false);
}

I had this code in the main loop. Without the GC.Collect function, the program was running with about 10MB of RAM. But with the GC.Collect function, it is running with 6MB of RAM.

And then my question comes, why didn't the GC automatically delete the variable after it has been written to the console?

Upvotes: 1

Views: 108

Answers (1)

Baldrick
Baldrick

Reputation: 11850

There are different ways to clean up unused memory in different languages / frameworks.

In C++ land you have (for example) reference counted smart pointers, which automatically call delete on their pointers when their count hits zero. If that's the behavior you're expecting in the .NET world, you'll be disappointed! :)

The .NET GC model is very different. To save you from having to worry about manually managing your memory, the CLR takes care of tracking which references are in use, and cleans up memory as needed. However, monitoring and checking which references are in use is a relatively expensive process. The garbage collector therefore does not run continuously. It kicks in, for example, when there's memory pressure (and in other situations, but this is of course a simplification).

The short answer is basically: Let the garbage collector do its job. It's a very smart and highly optimized system, and you should rarely (if ever) have to manually trigger garbage collection yourself.

Upvotes: 3

Related Questions