{"id":290,"date":"2014-09-04T12:53:49","date_gmt":"2014-09-04T12:53:49","guid":{"rendered":"http:\/\/mairwa.com\/wordpress\/?p=290"},"modified":"2014-09-04T12:53:49","modified_gmt":"2014-09-04T12:53:49","slug":"memory-management-in-net","status":"publish","type":"post","link":"http:\/\/mairwa.com\/wordpress\/?p=290","title":{"rendered":"Memory management in .Net"},"content":{"rendered":"<p>main concern for any application whether application is window based or web based. In .Net, CLR has garbage collector that executes as a part of our program and responsible for reclaiming the memory of no longer used objects. Garbage collector free the memory for objects that are no longer referenced and keeps the memory for future allocations.<\/p>\n<h2>Advantage of Garbage Collector<\/h2>\n<ol>\n<li>Allow us to develop an application without having worry to free memory.<\/li>\n<li>Allocates memory for objects efficiently on the managed heap.<\/li>\n<li>Reclaims the memory for no longer used objects and keeps the free memory for future allocations.<\/li>\n<li>Provides memory safety by making sure that an object cannot use the content of another object.<\/li>\n<\/ol>\n<h2>Memory Allocation in Managed Heap<\/h2>\n<p>The managed heap is a series of allocated memory segments (approx 16Mb in size each) to store and manage objects. The memory for newly created object is allocated at the next available location on the managed heap. If there is available free memory, the garbage collector doesn&#8217;t search the dead objects for memory reclaim and memory allocations has been done very fast. If the memory is insufficient to create the object, the garbage collector search the dead objects for memory reclaim for the newly object.<\/p>\n<div><img decoding=\"async\" alt=\"\" src=\"http:\/\/www.dotnet-tricks.com\/Content\/images\/netframework\/gcheap.png\" \/><\/div>\n<p>An object is created using the new operator. This operator first makes sure that the bytes required by the new object fit in the reserved region (committing storage if necessary). If the object fits, <b>NextObjPtr<\/b> points to the object in the heap and object&#8217;s constructor is called and the new operator returns the address of the object.<\/p>\n<h2>Key points about Garbage Collector<\/h2>\n<ol>\n<li>All objects in the heap are allocated from one contiguous range of memory address and heap is divided into generations so that it is easy to eliminate the garbage objects by looking at only a small fraction of the heap.<\/li>\n<li>Gen 0 and Gen 1 occupy a single segment known as the ephemeral segment. Gen 2 is a set of further segments and the large object heap is yet another group of segments.<\/li>\n<li>Almost, all objects with-in a generation are of the same age.<\/li>\n<li>The newest objects are created at higher memory address while oldest memory objects are at lowest memory address with in the heap.<\/li>\n<li>The allocation pointer for the new objects marks the boundary between the allocated and free memory.<\/li>\n<li>Periodically the heap is compacted by removing the dead objects and sliding up the live objects towards the lower memory address end of the heap as shown in above fig.<\/li>\n<li>The order of objects (after memory reclaims) in memory remains the same as they were created.<\/li>\n<li>There are never any gaps among the objects in the heap.<\/li>\n<li>Only some of the free memory is committed when required and more memory is acquired from the OS in the reserved address range.<\/li>\n<\/ol>\n<h2>Generations in Managed Heap<\/h2>\n<p>The managed heap is organized into three generations so that it can handle short lived and long lived objects efficiently. Garbage collector first reclaim the short lived objects that occupy a small part of the heap.<\/p>\n<div><img decoding=\"async\" alt=\"\" src=\"http:\/\/www.dotnet-tricks.com\/Content\/images\/netframework\/gcheapgen.png\" \/><\/div>\n<ol>\n<li>\n<h2>Generation 0<\/h2>\n<p>This is the youngest generation and contains the newly created objects. Generation 0 has short-lived objects and collected frequently. The objects that survive the Generation 0 are promoted to Generation 1.<\/p>\n<p><b>Example :<\/b> A temporary object.<\/li>\n<li>\n<h2>Generation 1<\/h2>\n<p>This generation contains the longer lived objects that are promoted from generation 0. The objects that survive the Generation 1 are promoted to Generation 2. Basically this generation serves as a buffer between short-lived objects and longest-lived objects.<\/li>\n<li>\n<h2>Generation 2<\/h2>\n<p>This generation contains the longest lived objects that are promoted from generation 1 and collected infrequently.<\/p>\n<p><b>Example :<\/b> An object at application level that contains static data which is available for the duration of the process.<\/li>\n<\/ol>\n<h2>Garbage Collector Working Phase<\/h2>\n<ol>\n<li>\n<h2>Marking Phase<\/h2>\n<p>In this phase garbage collector finds and creates a list of all live objects.<\/li>\n<li>\n<h2>Relocating Phase<\/h2>\n<p>In this phase garbage collector updates the references to the objects that will be compacted.<\/li>\n<li>\n<h2>Compacting Phase<\/h2>\n<p>In this phase garbage collector reclaims the memory occupied by the dead objects and compacts the surviving objects. The compacting phase moves the surviving objects toward the older end of the memory segment.<\/li>\n<\/ol>\n<div><img decoding=\"async\" alt=\"\" src=\"http:\/\/www.dotnet-tricks.com\/Content\/images\/netframework\/gcheapgenreclaim.png\" \/><\/div>\n<h4>Note<\/h4>\n<ol>\n<li>The large object heap is not compacted, because copying large objects imposes a performance penalty.<\/li>\n<\/ol>\n<h2>Garbage Collection Algorithm<\/h2>\n<p>Garbage collector determine whether any object in the heap is dead or not being used by the application. If such objects exist then memory used by these objects can be reclaimed. But how garbage collector know about these objects?<\/p>\n<p>Each and every application has a set of roots and these identify the storage locations for the objects on the managed heap.<\/p>\n<p><b>Example :<\/b> All the global, static objects pointers and all the local variable\/ parameter object pointers on the thread&#8217;s stack in the application are considered part of the application&#8217;s roots. More over any CPU registers containing pointers to objects in the managed heap are also considered a part of the application&#8217;s roots.<\/p>\n<p>The list of active roots is maintained by the JIT compiler and CLR, and is made accessible to the garbage collector&#8217;s algorithm.<\/p>\n<h3>Memory Reclaim Process<\/h3>\n<p>Now the garbage collector starts go through the roots and make a graph of all the objects reachable from the roots. The below fig. shows a heap with allocated objects. In this heap the application roots directly refer to the objects 1,3,4,6 and object 3 &amp; 6 refers to the objects 8 &amp; 10. Hence all these objects will become the part of the live objects graph.<\/p>\n<div><img decoding=\"async\" alt=\"\" src=\"http:\/\/www.dotnet-tricks.com\/Content\/images\/netframework\/gcalgo.png\" \/><\/div>\n<p>The objects which are not reachable from application&#8217;s roots, are considered as garbage since these are not accessible by the application. In above heap objects 2,5,7,9 will be considered as dead objects.<\/p>\n<div><img decoding=\"async\" alt=\"\" src=\"http:\/\/www.dotnet-tricks.com\/Content\/images\/netframework\/gcalgograph.png\" \/><\/div>\n<p>The garbage collector then remove the dead objects from the heap and live objects will move toward the older end of the memory segment as shown in below fig. Garbage collector also updates all the references(including root references) to the moving objects in the heap.<\/p>\n<div><img decoding=\"async\" alt=\"\" src=\"http:\/\/www.dotnet-tricks.com\/Content\/images\/netframework\/gcalgo1.png\" \/><\/div>\n<div>Reference : <a href=\"http:\/\/msdn.microsoft.com\/en-us\/magazine\/bb985010.aspx\" target=\"_blank\">http:\/\/msdn.microsoft.com\/en-us\/magazine\/bb985010.aspx<\/a><\/div>\n<div><\/div>\n<div>\n<div>\n<div><strong>Difference between Finalize &amp; Dispose Method<\/strong><\/div>\n<div><\/div>\n<div>\n<div><strong>Finalize&#8211;<\/strong>Used to free unmanaged resources like files, database connections, COM etc. held by an object before that object is destroyed.<\/div>\n<div><strong>Dispose&#8211;<\/strong>It is used to free unmanaged resources like files, database connections, COM etc. at any time.<\/div>\n<\/div>\n<div>\n<div><strong>Finalize&#8211;<\/strong>Internally, it is called by Garbage Collector and cannot be called by user code.<\/div>\n<div><strong>Dispose-<\/strong>-Explicitly, it is called by user code and the class implementing dispose method must implement IDisposable interface.<\/div>\n<\/div>\n<div>\n<div><strong>Finalize&#8211;<\/strong>It belongs to Object class.<\/div>\n<div><strong>Dispose&#8211;<\/strong>It belongs to IDisposable interface.<\/div>\n<\/div>\n<div>\n<div><strong>Finalize&#8211;I<\/strong>mplement it when you have unmanaged resources in your code, and want to make sure that these resources are freed when the Garbage collection happens.<\/div>\n<div><strong>Dispose&#8211;<\/strong>Implement this when you are writing a custom class that will be used by other users.<\/div>\n<\/div>\n<div>\n<div><strong>Finalize&#8211;<\/strong>There is performance costs associated with Finalize method.<\/div>\n<div><strong>Dispose&#8211;<\/strong>There is no performance costs associated with Dispose method.<\/div>\n<div><\/div>\n<div><strong>Finalize<\/strong>&#8212;<\/div>\n<\/div>\n<div>\n<div><b>For Example,<\/b><\/p>\n<ol>\n<li>\/\/ Implementing Finalize method<\/li>\n<li>public class MyClass<\/li>\n<li>{<\/li>\n<li>\/\/At runtime C# destructor is automatically Converted to Finalize method.<\/li>\n<li>~MyClass ()<\/li>\n<li>{<\/li>\n<li>\/\/TO DO: clean up unmanaged objects<\/li>\n<li>}<\/li>\n<li>}<\/li>\n<\/ol>\n<\/div>\n<div><strong>Dispose&#8212;<\/strong><\/div>\n<div><b>For Example,<\/b><\/p>\n<ol>\n<li>\/\/ Implementing Dispose method<\/li>\n<li>public class MyClass : IDisposable<\/li>\n<li>{<\/li>\n<li>private bool disposed = false;<\/li>\n<li><\/li>\n<li>\/\/Implement IDisposable.<\/li>\n<li>public void Dispose()<\/li>\n<li>{<\/li>\n<li>Dispose(true);<\/li>\n<li>}<\/li>\n<li><\/li>\n<li>protected virtual void Dispose(bool disposing)<\/li>\n<li>{<\/li>\n<li>if (!disposed)<\/li>\n<li>{<\/li>\n<li>if (disposing)<\/li>\n<li>{<\/li>\n<li>\/\/TO DO: clean up managed objects<\/li>\n<li>}<\/li>\n<li><\/li>\n<li>\/\/TO DO: clean up unmanaged objects<\/li>\n<li><\/li>\n<li>disposed = true;<\/li>\n<li>}<\/li>\n<li>}<\/li>\n<li>}<\/li>\n<\/ol>\n<\/div>\n<\/div>\n<\/div>\n<h4>Note<\/h4>\n<ol>\n<li>You cannot override the Finalize method in the C# or C++ languages. But you can override Finalize method in VB.NET since it does not support destructor.<\/li>\n<li>You should not implement a Finalize method for managed objects, because the garbage collector cleans up managed resources automatically.<\/li>\n<li>A Dispose method should call the GC.SuppressFinalize() method for the object of a class which has destructor because it has already done the work to clean up the object, then it is not necessary for the garbage collector to call the object&#8217;s Finalize method.<\/li>\n<\/ol>\n<ol>\n<li>\/\/ Using Dispose and Finalize method<\/li>\n<li>public class MyClass : IDisposable<\/li>\n<li>{<\/li>\n<li>private bool disposed = false;<\/li>\n<li><\/li>\n<li>\/\/Implement IDisposable.<\/li>\n<li>public void Dispose()<\/li>\n<li>{<\/li>\n<li>Dispose(true);<\/li>\n<li>GC.SuppressFinalize(this);<\/li>\n<li>}<\/li>\n<li><\/li>\n<li>protected virtual void Dispose(bool disposing)<\/li>\n<li>{<\/li>\n<li>if (!disposed)<\/li>\n<li>{<\/li>\n<li>if (disposing)<\/li>\n<li>{<\/li>\n<li>\/\/ TO DO: clean up managed objects<\/li>\n<li>}<\/li>\n<li><\/li>\n<li>\/\/ TO DO: clean up unmanaged objects<\/li>\n<li><\/li>\n<li>disposed = true;<\/li>\n<li>}<\/li>\n<li>}<\/li>\n<li><\/li>\n<li>\/\/At runtime C# destructor is automatically Converted to Finalize method<\/li>\n<li>~MyClass()<\/li>\n<li>{<\/li>\n<li>Dispose(false);<\/li>\n<li>}<\/li>\n<li>}<\/li>\n<\/ol>\n<\/div>\n<div><\/div>\n","protected":false},"excerpt":{"rendered":"<p class=\"excerpt\">main concern for any application whether application is window based or web based. In .Net, CLR has garbage collector that executes as a part of our program and responsible for reclaiming the memory of no longer used objects. Garbage collector free the memory for objects that are no longer referenced and keeps the memory for future allocations. Advantage of Garbage&hellip; <a href=\"http:\/\/mairwa.com\/wordpress\/?p=290\">Read more &rarr;<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,4,5,7],"tags":[],"class_list":["post-290","post","type-post","status-publish","format-standard","hentry","category-c-vb","category-ado-net-entity-framework","category-architecture","category-c","xfolkentry"],"_links":{"self":[{"href":"http:\/\/mairwa.com\/wordpress\/index.php?rest_route=\/wp\/v2\/posts\/290","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/mairwa.com\/wordpress\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/mairwa.com\/wordpress\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/mairwa.com\/wordpress\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/mairwa.com\/wordpress\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=290"}],"version-history":[{"count":0,"href":"http:\/\/mairwa.com\/wordpress\/index.php?rest_route=\/wp\/v2\/posts\/290\/revisions"}],"wp:attachment":[{"href":"http:\/\/mairwa.com\/wordpress\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=290"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/mairwa.com\/wordpress\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=290"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/mairwa.com\/wordpress\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=290"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}