Saturday, June 8, 2013

GC.Collect

We know that Garbage Collection is automatic and is managed by the runtime, but there might be situation when you want to explicitly force Garbage Collection to happen from your applications. The GC.Collect() method does exactly this, it forcefully initiates a Garbage Collection run.

In general it is not advisable to use GC.Collect() from your code, since the runtime by itself will determine the most optimal time and way to run Garbage Collection. However you can still use GC.Collect() if you are sure that there are no critical operations planned to happen for the next few seconds.

The following are some of the situations when you might want to call GC.Collect()

1. Before you start a critical operation, if you feel that Garbage Collection might start in between your critical operation and hinder the performance of your critical operation, then it is advisable to call GC.Collect() before you start your critical operation so that it will not be called again when your critical operation gets started.

2. When you are sure that the system will be idle for the next few seconds or so, and if you want to make use of the idle time to reclaim unused memory space then you can call GC.Collect() and reclaim unused memory in your idle time.

3. If you plan to start a memory intensive operation, there are more chances that Garbage Collection might start running as you keep adding more objects to the Heap, in these situations you can call GC.Collect() before you start your memory intensive operation to avoid low memory risk while your operation is in progress.

Search Flipkart Products:
Flipkart.com

No comments: