Garbage collector runs when the .Net environment determines that it is required to run. However, you can force the garbage collector to run by calling the GC.Collect() method. there are no guarantees that an unreferenced object will be disposed in the first run of the garbage collector. Objects that do not have a destructor or finalizer get removed in a single pass, whereas objects with destructors need two passes to be disposed. at first it get call the destructor and at the second part it will delete that perticular object.
The .Net Garbage Collector is optimize for following situation.
1. Objects that have lived the longest are least likely to be become free.
2. Objects allocated together are often used together.
3. Objects that were recently allocated are most likely to be freed.
for Distroying purpose we have Finalizer Method which works as:
in C#, the finalizer is a protected method as shown below
protected void Finalize()
{
base.Finalize();
}
but Instead of declaring a Finalizer, exposing a Dispose method is considered as good.
Dispose
by calling GC.SuppressFinalize() we can dispose memory like
public void Dispose()
{
GC.SuppressFinalize(this);
}
but in The Microsoft.NET CLR (Common Language Runtime) requires that all resources be allocated from the managed heap. You never free objects from the managed heap-objects are automatically freed when they are no longer needed by the application.
Garbage collection in .NET is done using tracing collection and specifically the CLR implements the Mark/Compact collector.
there are two phases :
1)Find memory that can be reclaimed.
2)Move all the live objects to the bottom of the heap, leaving free space at the top.
at last we can say GC is necessarily slower than manual memory management.Programs with GC are huge and bloated; GC isn't suitable for small programs or systems.
No comments:
Post a Comment