Memory Allocation

Value types and reference types are differently allocated in memory. Value types are allocated in the Stack. The Stack is a memory area where methods are executed according to the last-in, first-out manner. The first method pushed to the Stack is the application entry point; that is, the Main method. When Main invokes other methods, the CLR creates a sort of restore point and pushes those methods to the Stack. When the method needs to be executed, data required by that method is also pushed to the Stack. When a method completes, the CLR removes (popping) it from the Stack together with its data, restoring the previous state. Because of this ordered behavior, the Stack is efficient, and the Common Language Runtime can easily handle it. Consider the following line of code, declaring a variable of type Integer, therefore a value type:

Dim anInteger As Integer = 5

Figure 4.4 shows how the anInteger variable is allocated in the Stack.

Figure 4.4 Value types are allocated in the Stack.

image

On the contrary, reference types are allocated in a memory area named Managed Heap. Different from the Stack, in the Managed Heap objects are allocated and deallocated randomly. This provides fast allocation but requires more work for the CLR. To keep things ordered, the CLR needs two instruments: Garbage Collector and Memory Manager. We provide details about this architecture in Chapter 8, “Managing an Object’s Lifetime.” At the moment we need to understand how reference types and their data are allocated. Consider the following lines of code, declaring a new version of the Person class and an instance of this class:

image

As you can see, there is now a property in this class (Age) that is a value type. The instance of the class will be allocated in the Heap, whereas its reference (onePerson) will be allocated in the Stack. Figure 4.5 provides a visual representation of this scenario.

Figure 4.5 Reference types are allocated in the Heap, whereas their address resides in the Stack.

image

Because the Person class handles a value type in one of its properties, such value types stay in the Stack. Figure 4.6 completes this overview. In the second part of this book, we will have different opportunities to explore reference types and memory management when discussing the object’s lifetime.

Figure 4.6 Complete overview of memory allocation for value and reference types.

image

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.15.84