Coffeehouse Post

Single Post Permalink

View Thread: Patrick Dussud interview next week: Questions?
  • User profile image

    sushovande wrote:
    Is it true that I should not call GC.Collect() manually because that would adversely affect the garbage collection schedule? How badly will it affect? Is it beneficial to call Collect() just before allocating a large chunk of memory?

    The only time to call GC.Collect() (or its Java equivalent) is when you're absolutely certain of what you are doing.  For instance, if you've just finished using 10,000 objects (or more, depending on size) you are never using again and you need to make a whole bunch more, then you might be wise to call it.  However, I'm reasonably sure that calling that function could just be ignored (in .NET or Java), as the run-time tends to know better than you do.  The vast majority of the time, you're not even working with enough dead objects that it is going to matter.  Garbage collection in .NET (in theory; of course, I read this back in version 1.0) only happens when you're running out or low on memory.

    (All of the following is based on my memory from a few years back.  I could be wrong)  Memory in the .NET runtime is different than what the OS does.  The OS does some tricks to track what parts of memory are in use, which takes much more time (relatively speaking) than .NET for allocations.  .NET just maintains a pointer to the top of the heap, and memory is allocated in chunks.  If you're running out, GC.Collect will find blocks of memory that aren't in use and compact.  I actually did a presentation on this way back in the day for the MSDN AA, but things could have changed.

    This would still be a good question though, because I get the impression that memory management is a bit of a mystery.  Covering how .NET works here would be good for all devs to know: knowing how to write code doesn't mean you know what is actually going on.  This is why I advocate everyone learning an honest to goodness assembly language like IA-32 or x64.  Studying C and C++ was great, but once I saw how things would translate down lower made great sense to me.  (Of course, individual instructions carry their own costs, knowing adder and shifter circuit designs shows why one is faster than the other)