Memory Allocation

Value types and reference types are allocated differently in memory. Value types are allocated in the stack. The stack is a memory area where methods are executed in 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 (pops) it from the stack together with its data and restores the previous state. Because of this ordered behavior, the stack is efficient, and the CLR can easily handle it. Consider the following line of code, which declares a variable of type Integer and therefore a value type:

Dim anInteger As Integer = 5

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

Image

FIGURE 4.4 Value types are allocated in the stack.

Reference types are allocated in a memory area called the managed heap. Unlike how objects are treated in the stack, objects in the managed heap 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: the garbage collector and the memory manager. We provide details about this architecture in Chapter 8, “Managing an Object’s Lifetime.” At the moment you just need to understand how reference types and their data are allocated. Consider the following lines of code, which declare a new version of the Person class and an instance of this class:

Class Person
    Property Name As String
    Property Age As Integer
End Class
Dim onePerson As New Person
onePerson.Name = "Alessandro Del Sole"
onePerson.Age = 37

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, and its reference (onePerson) will be allocated in the stack. Figure 4.5 provides a visual representation of this scenario.

Image

FIGURE 4.5 Reference types are allocated in the heap, whereas their addresses reside in the stack.

The Person class handles a value type in one of its properties, and such value types stay in the stack. Figure 4.6 completes this overview of value and reference types. In Part II, “Object-Oriented Programming with Visual Basic 2015,” you will have more opportunities to explore reference types and memory management when discussing the object’s lifetime.

Image

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

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

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