GC.Collect()

I can see that several people have gone extreme about not recommending to call GC.Collect.

GC.Collect is there for a reason, here are my recommendation of when and why to call GC.Collect.

  1. In General, don’t worry about calling it, GC tunes itself very well and will do the right thing.

  2. Sometimes, you end up in situation where you know for sure that this is the right time to call it, the situation you described above is exactly the right time to call it, in fact Asp.Net calls GC.Collect at certain points that are similar to what you described.

  3. The GC is smart about calling GC.Collect, if you called GC.Collect, the GC can override your decision and still doesn’t collect ( you have to set a flag when you call GC.Collect to choose this behavior), this is the recommended way of calling GC.Collect, since you are still letting the GC decides if it is a good time to collect.

  4. Don’t take my recommendation is a general statement for calling GC.Collect, you should always avoid calling it, unless you REALLY sure you need to call it, situation like the one you described is exactly why GC.Collect is there.

  5. The benefit you will get from calling it is freeing the garbage quickly, generally you will care about this situation if

    1. You are in low memory situation and want to be eager about collection, if you are in low memory situation, the GC will be aggressive anyway and will kick in automatically if the memory pressure is high on the machine
    2. If you want to avoid getting in low memory situation and you want to collect eagerly.

Hope this helps.
Thanks

Leave a Comment