Reputation: 8675
How do I free memory in .NET? Is it correct to do:
myArray = null;
GC.Collect();
or
myArray = Nothing
GC.Collect()
Or should I always wait for garbage collection to occur when the OS is ready to?
Thanks.
Upvotes: 0
Views: 583
Reputation: 11745
Why you should not care, instead relax and keep writing your code beacuse its already taken care by this
Upvotes: 0
Reputation: 106236
According the MSDN's page on GC.Collect():
All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.
This suggests the memory you removed the reference from may be released if there are no other references. Still, you should be aware that the function may take a long time (from a program perspective) to run, so you probably don't want to call it yourself: if you end up trying to do it too often it may do unnecessary redundant work and slow your application down dramatically. If it's beneficial, it should happen soon anyway. If you really want deterministic destruction, consider putting a bit of C++ in and using the "real" heap instead of the GC-ed one.
Upvotes: 0
Reputation: 2845
As a best practice, just wait for the GC to collect unused resources. The GC is intelligent enough to know when the collection should occur. Forcing the GC to run costs great price.
Upvotes: 0
Reputation: 14874
None of this will do what you want. In managed runtime, releasing memory used by a reference is non-deterministic and it solely depend on when the Garbage Collector runs and with which policy. So for regular types don't do anything, just relax and write your business code.
Upvotes: 4