Game Development Reference
Another performance benefit of the managed garbage collector comes from local-
ity of reference. With the traditional unmanaged heap, memory was allocated
wherever free space was found. Sometimes related data could be separated by
megabytes. However, the managed heap allocates consecutive objects in a contigu-
ous manner. There is an assumption that short-lived objects tend to have strong
relationships with each other and are typically accessed around the same time.
Many situations will allow all the related objects to reside in the CPU cache, which
provides extremely fast access without having cache misses that require RAM access.
Collecting the Garbage
Garbage collection is automatically called by the CLR runtime, alleviating the bur-
den of you having to explicitly do it yourself. It is important to know when and
how collections occur in order to optimize effectively. Understanding how the GC
works internally can offer some great insight into ways that your applications
should be built to maximize memory management performance.
Developers transitioning from an unmanaged to a managed environment are
often concerned with the performance of automatic memory management, more
specifically, how the GC compares to the explicit management of memory like in
When a memory allocation occurs, the CLR garbage collector determines whether
or not a collection should occur. The GC looks at different factors, such as the cur-
rent size of each generation, the size of each collection, and the size of the data that
must be allocated. The GC then uses a heuristic evaluation to decide if a collection
should occur. CLR garbage collection is as fast as or faster than C++ until a col-
lection occurs. Essentially, a collection occurs when generation 0 does not have
enough free space to accommodate a new object.
Collection usually occurs because:
The application explicitly calls the collection routine of the GC.
Generation 0 reaches max storage size.
An AppDomain is unloaded by the CLR.
The CLR itself is unloaded.
Each application has a set of roots , which identify storage locations for objects on
the managed heap and objects that are set to null . These roots are made accessible
by the garbage collector to determine whether a particular object is strongly refer-
enced or if it should be collected (garbage).