30.06.2013 Views

Under the Hood of .NET Memory Management - Simple Talk

Under the Hood of .NET Memory Management - Simple Talk

Under the Hood of .NET Memory Management - Simple Talk

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 1: Prelude<br />

1 int i=12;<br />

2 ArrayList lst=new ArrayList();<br />

3 // ArrayList Add method has <strong>the</strong> following signature<br />

4 // int Add(object value)<br />

5 lst.Add(i); // Boxing occurs automatically<br />

6 int p=(int)lst[0]; // Unboxing occurs<br />

Listing 1.10: Boxing a value type.<br />

Listing 1.10 demonstrates how boxing and unboxing can sneakily occur, and I bet you've<br />

written similar code at some point. Adding an integer (value type) to <strong>the</strong> ArrayList will<br />

cause a boxing operation to occur because, to allow <strong>the</strong> array list to be used for all types<br />

(value and reference), <strong>the</strong> Add method takes an object as a parameter. So, in order to add<br />

<strong>the</strong> integer to <strong>the</strong> ArrayList, a new object has to be allocated onto <strong>the</strong> heap.<br />

When <strong>the</strong> integer is accessed in Line 6, a new stack variable "p" is created, and its value set<br />

to <strong>the</strong> same value as <strong>the</strong> first integer in <strong>the</strong> ArrayList.<br />

In short, a lot more work is going on than is necessary, and if you were doing this in a<br />

loop with thousands <strong>of</strong> integers, <strong>the</strong>n performance would be significantly slower.<br />

More on <strong>the</strong> Heap<br />

Now that we've had our first look at <strong>the</strong> heap(s), let's dig a little deeper.<br />

When a reference type is created (class, delegate, interface, string, or object),<br />

it's allocated onto <strong>the</strong> heap. Of <strong>the</strong> four heaps we've seen so far, .<strong>NET</strong> uses two <strong>of</strong> <strong>the</strong>m to<br />

manage large objects (anything over 85 K) and small objects differently. They are known<br />

as managed heaps.<br />

To make it <strong>the</strong> worry-free framework that it is, .<strong>NET</strong> doesn't let you allocate objects<br />

directly onto <strong>the</strong> heap like C/C++ does. Instead, it manages object allocations on your<br />

behalf, freeing you from having to de-allocate everything you create. By contrast, if a<br />

27

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!