Over a million developers have joined DZone.

Memory Management for .Net

DZone's Guide to

Memory Management for .Net

Use the Garbage Collection Pattern method to limit or eliminate memory leaks in your .Net applications and provide a more efficient developer experience.

· Performance Zone ·
Free Resource

Sensu is an open source monitoring event pipeline. Try it today.

Memory Management in .Net Framework

Automatic memory management is one of the services that the common language runtime provides during Managed Execution. The CLR’s garbage collector handled the allocation and release of memory for an application, which eliminates common problems such as missing to free an object and causing a memory leak, or attempting to access memory for an object that has already been released.

Garbage Collection Pattern

Mismanagement of memory is one of the most common problems that goes unnoticed during development and results in issues which are very difficult to idenity. Memory issues arise since modern programming languages gives very limited access to memory and do not provide indicators to identify if memory is accessed in the optimal way, thus results in frequent instances of memory leaks and dangling pointers.

Memory issues have a very high impact in application maintenance as they tend to have global impact to the entire application and can cause the entire system to crash and give limited traces of where the defect occured.

The Garbage Collection Pattern addresses memory access defects in a clean and simple way as far as the application programmer is concerned. The standard implementation of this pattern does not address memory fragmentation (refer to the Garbage Compactor Pattern), but it does allow the system to operate properly in the face of poorly managed memory.

Garbage Collection Pattern can potentially eliminate memory leaks in application code by taking advantage of dynamic memory allocation. Quite often application developers err in how memory should be handled. More than handling how memory is deallocated, the Garbage Collection Pattern eliminates these issues by encapsulating the memory deallocation from the programmers and thus developers need not handle it explicitly in most of the application code scenarios. By relieving the programmer from explicit memory handling in most application code scenario, the source of common issues are elimited to a large extent. 

Though the Garbage Collection Pattern has huge benefits, it does come with a cost: it adds up to the run-time overheads to identify and removes inaccessible memory to reclaim free memory space.


The GC Pattern largely addresses the bottleneck in terms of avoiding memory leaks in the application to a large extent. Many high-availability/high-reliabilty systems must function for long periods of time without being periodically shut down. Since memory leaks lead to unstable behavior, it is required to completely avoid them in such systems. Furthermore, reference counting Smart Pointers have the disadvantages that they require programmer discipline to use correctly and cannot be used when there are cyclic object references.

Pattern Structure

In Mark and Sweep, garbage collection takes place in two phases:

  • Mark - marking memory

  • Sweep - Reclaim memory

Objects are marked as live when they created and in use. The marking phase starts in response to a low memory or an explicit request to perform garbage collection. In the marking phase, each of the root objects is searched to find all live objects. Objects that cannot be reached in this way are marked as dead. In the subsequent sweep phase, all the objects marked as dead are reclaimed. The garbage collector must stop normal processing before performing its duties, reducing the predictability of real-time systems.

Collaboration Roles


The Client is the user-defined object that allocates memory (generally, although not necessarily, in the form of objects). It is a subclass of Collectable and contains pointers to derived objects, allowing the garbage collector to search from the root objects to all derived objects. When created, the object is marked as live with a isLive attribute, inherited from Collectable. On the second pass, all objects not marked as live are removed—that is, added back to the heap free memory.


This is the base class for Client, and it provides the isLive Boolean attribute used during the garbage collection process.

Free Block List

A list of free blocks from which requests for dynamic memory are fulfilled.

Garbage Collector

The Garbage Collector manages the reclamation of memory by searching the object space starting with the root objects, looking at all blocks to ensure their liveness, and removing all those that are no longer live—in other words, those that cannot be reached in some fashion from a root or derived object.


The Heap is the owner of all the Memory Blocks and the Free Block List.

Memory Block

The Memory Block is just like it sounds: a block (normally of arbitrary size, in which case it contains a size parameter) of memory, usually, although not necessarily, associated with an object. Memory Blocks may be pointed to by the Free Block List, in which case they are not currently being pointed to by a Client or may be pointed to by a Client, in which case they are not pointed to by the Free Block List. Hence, the {exclusive} constraint on the relations to those classes.


This architectural pattern removes the vast majority of memory-related problems by effectively eliminating memory leaks and dangling pointers. It is still possible to do bad pointer arithmetic, but they account for a relatively small number of defects compared to the first two memory-management defects. Further, there is much less need to do pointer arithmetic when memory is collected and managed for you. The use of this pattern removes these user defects by eliminating reliance on the user to correctly deallocate memory.

The garbage collector runs episodically when a "low-memory" condition is detected and deallocates all inaccessible memory. Following garbage collection, all non-NULL pointers and references are valid, and all unreferenced memory is freed. The pattern correctly identifies and handles circular references, unlike the Smart Pointer Pattern.

Since this pattern uses a two-pass mark-and-sweep algorithm, it takes a nontrivial amount of time to do a complete memory cleanup. This has two negative consequences. First, considerable processing time and effort may be required to perform the memory reclamation, and it cannot in general, be predicted how much time and effort will be required. Second, because it is done in response to a low-memory condition (such as a request for memory that cannot be fulfilled), when it occurs is likewise unpredictable. This means that while the approach scales up to large-scale system well in terms of managing complexity, it may not work well in systems with hard real-time constraints.

Another difficulty with this approach is that it does not affect fragmentation, a key problem in systems that must run for long periods of time. Memory will be reclaimed properly, but it will result in fragmented free space. This means that although enough memory may be free to fulfill a request for memory, there may not be a single contiguous block available to fulfill the request. In fact, with this pattern (and most other memory management patterns) fragmentation increases monotonically the longer the system runs. 

Implementation Strategies

As with all such patterns, the simplest way to use this pattern is to buy it. Some languages, such as Java, provide memory management systems that use garbage collection out of the box. Where such languages are not available, the implementation of such a memory management schema can be done easily in the naïve case and with more difficulty in the more optimized case.

A common optimization is to allow the application objects to explicitly request a garbage collection pass when it is convenient for the application, such as when the application is quiescent. For example, if the concurrency model is managed by a cyclic executive (see the Cyclic Executive Pattern), then at the end of the cycle, if there is sufficient time, a memory cleanup may be performed. If it cannot be guaranteed that the garbage collection will complete before the next cycle occurs, the garbage collector may be preemptable, so that it is stopped prior to completion, allowing the application to run and meet its deadlines. When using such a strategy, be careful that you do not assume that the object marked as live on the previous pass has remained live.

Related Patterns

When the inherent unpredictability of the system cannot be tolerated, another approach, such as the Smart Pointer Pattern or Fixed Size Allocation Pattern, should be used. To eliminate memory fragmentation, the Garbage Compactor Pattern works well. The Static Allocation Pattern does not have fragmentation, and the Fixed Sized Allocation Pattern does its best to minimize fragmentation. The Smart Pointer Pattern cannot handle circular references, but the Garbage Collection and Garbage Compactor Patterns do.

Sensu: workflow automation for monitoring. Learn more—download the whitepaper.

memory management ,memory leaks ,garbage collection pattern ,.net application ,performance ,dangling pointers

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}