Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

.NET

Optimizing Memory in .NET Applications


Working with the Garbage Collector

As most developers know by now, the mechanism by which the CLR reclaims memory from applications is called the garbage collector. The .NET garbage collector works by starting with roots, base object references that are not embedded inside another object. For example, static and global pointers are application roots. The garbage collector starts with these roots, and traces references to other objects on the heap. It creates a graph of all objects that are reachable from these root components.

Any object that is not in this graph is considered to be no longer in use and is added back to the heap. The garbage collector accomplishes this by walking through the heap and identifying objects that are not a part of one of these graphs. The garbage collector marks these addresses and keeps track of them until it has walked through the entire heap or some defined portion of it.

During this process, the garbage collector also compacts the heap so that fragmentation doesn’t prevent an allocation due to the lack of a large enough memory block. Additionally, this compaction leaves free memory at the top of the heap, where it can be reallocated simply by moving the heap pointer. The garbage collector doesn’t have to walk a linked list to find memory blocks, so allocations are fast compared to unmanaged languages.

Compaction involves relocating memory blocks down to the bottom of the heap using the memcopy function, then adjusting all of the pointers from root structures so that they refer to the new addresses. The garbage collector also must change any pointers from other objects in the application to reflect the new addresses.

For efficiency reasons, the garbage collector also uses a concept called "generations" in reclaiming memory. There are a total of three generations, labeled 0, 1, and 2. When objects are first allocated at the beginning of application execution, the garbage collector refers to this part of the heap as generation 0. Newly created objects always go into generation 0. These "young" objects have not yet been examined by the garbage collector.

The garbage collector checks this generation first, so it can reclaim more memory, and more quickly, than if it treated all heap memory the same. If there are references to the object when the next collection occurs, the object gets moved to generation 1. In this way, only a part of the memory heap—the part with the greatest potential to yield free memory—needs to be checked at any one time, a strategy that can improve the performance of individual collections.

When more objects are added to the heap, the heap fills and a garbage collection must occur. When the garbage collector analyzes the heap, it builds the graph of live objects, and collects the rest. The objects that have survived a collection are now older and are considered to be in generation 1. The garbage collector maintains a table of objects and when they were accessed. It identifies which objects haven’t been modified and are eligible for garbage collection.

As even more objects are added to the heap, these new, young objects are placed in generation 0. When the time comes for the next garbage collection, the collector determines which old objects have been written to since the last collection. The garbage collector checks the references to these specific old objects to see if they refer to any new objects. If a root or object refers to an object in an old generation, the garbage collector can ignore any of the older object’s inner references, decreasing the time required to build the graph of reachable objects. Collecting newer objects first can also reduce page faulting and improve performance, because newer objects are stored contiguously in the heap.

Likewise, if an object survives a generation 1 garbage collection, it is promoted to generation 2. When a collection occurs, the three generations of heap memory generations 0, 1, and 2 are checked in succession. If checking generation 0 reclaims enough memory, garbage collection ceases. If not, the garbage collector then checks generation 1, and finally generation 2. In practice, generation 2 objects are long-lived, and are often not collected until the application finishes and exits.

You can also work with the garbage collector to optimize memory use through weak references. Unlike strong references, the .NET Framework can garbage collect weak references if memory is low.

First, you establish a strong reference by subclassing and initializing an object, then apply a weak reference through the appropriate .NET Framework call. If memory use remains low, the weak reference is sufficient to prevent that object from being garbage collected.

If memory becomes scarce, the garbage collector can dispose of the object and reclaim the memory. When might you use a weak reference? One example is if you create a structure that is useful for efficiency reasons, such as a search tree. The first time it’s used, you have to take the performance hit to create the tree. After that, you might want to keep it around in case the application uses it again, but not at the expense of poor performance elsewhere in the application. So with the weak reference, the .NET Framework offers the option of designating a structure that is, in effect, the first to go if memory runs short.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.