0

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?

4
  • 3
    it does.. just not when it suits you, when its in the mood Commented Jun 12, 2018 at 7:53
  • 1
    You never know when the GC will actually start to clean after you Commented Jun 12, 2018 at 7:54
  • Note that the memory you are seeing is probably some buffer allocated by the Console.WriteLine(). Random doesn't allocate variables, and inl is in the stack. Commented Jun 12, 2018 at 7:55
  • 1
    The whole idea of garbage collection is that it is not usually deterministic, but it will happen at some point. The trigger could be an elapsed amount of time, a certain amount of memory used, or something else. In your example, you are forcing the collection to run immediately, instead of waiting for the garbage collection to occur of its own accord. Commented Jun 12, 2018 at 7:56

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.