Memory Management

 <  Day Day Up  >  

Memory allocated by Visual Basic .NET programs is managed by the .NET Framework runtime environment. There are two kinds of types in the Visual Basic .NET type system ” reference types and value types ”that are distinguished by the way in which the Framework manages the memory used by the type. Reference types are stored by the Framework on the system heap . The heap is a pool of memory that the Framework keeps available for programs to use when allocating memory. When a value is allocated on the heap, the Framework finds a chunk of free memory large enough to hold the value, stores the value on the heap, and then returns a reference to where the value is stored on the heap. Variables that hold a reference type contain only a reference to the value on the heap, not the value itself (see Figure 1-5).

Figure 1-5. A Reference Type Variable and the Heap

graphics/01fig05.gif

The Framework keeps track of all references to values on the heap and periodically reclaims memory on the heap by looking for values that are no longer being referenced and freeing them. This process is called garbage collection , and it ensures that the heap has memory available to fulfill allocation requests from the application.

In contrast to reference types, value types have values that are stored directly within another value, so they do not require allocating space on the heap (see Figure 1-6). Value types that are fields of a reference type are stored on the heap as part of the reference type; value types that are local variables or arguments are stored on the stack , which is a second pool of memory dedicated to local variables and method arguments.

Figure 1-6. A Value Type Variable

graphics/01fig06.gif

Because a value type value is always contained within another value, a value type never requires memory to be allocated for it. Variables that hold value types can always have values stored into them, whereas variables that hold reference types have to first allocate space to hold their value. Before storage is allocated to hold its value, a reference type variable contains the special value Nothing , which indicates that the variable does not refer to any value on the heap. Attempting to use a variable that contains Nothing generally will result in a System.NullReferenceException being thrown by the Framework.

 <  Day Day Up  >  


The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net