|< Day Day Up >|
Before we jump into classes and structures, however, it is necessary to take a step back for a moment and talk about memory. As discussed in Chapter 2, Basic Concepts, the .NET Framework provides many services to programmers, one of the most important of which is memory management . Because the Framework's method of managing memory on behalf of a program is central to how classes and structures work, it is worth spending a moment discussing how the Framework manages memory.
The Heap and the Stack
Information in a program can be stored in one of two places by the Framework: on the stack and on the heap . The stack is a pool of memory that can be used by local variables and method parameters; each time a method or property is executed, the Framework allocates space on the stack to store its locals and parameters. Since a method or property declares all its local variables and parameters at compile time, the amount of space allocated on the stack for a method or property is fixed at runtime and cannot change.
Programs that need to store a dynamic amount of information use the heap. The heap is a dynamic pool of memory that the Framework manages and makes available to programs to store information in at runtime. When a running program wishes to store a value on the heap, it gives the value to the Framework, which finds a place for the value on the heap, copies it there, and then gives back a reference to where the value was stored on the heap. Whenever the program wishes to access the value on the heap, then, it must use the reference to find the value (see Figure 9-1).
Figure 9-1. A Reference Type Variable and the Heap
The lifetime of values stored on the stack versus those stored on the heap is different. The lifetime of values on the stack is tied to the method or property in which they are declared ”for example, a local variable in a subroutine exists only as long as the subroutine is actually being executed; once the subroutine is exited, the local variable disappears. The lifetime of values on the heap, on the other hand, is determined by whether any references to them exist. The Framework keeps track of all the references that it has handed out to a particular value on the heap. It then periodically checks to see which values on the heap no longer have any active references to them and frees up the space that those values are using. This process is called garbage collection . It is important to keep in mind that the lifetime of a value on the heap is under the control of the Framework and not the programmer. Even when the last reference to a value on the heap disappears, the value will not be discarded until the next time the Framework does a garbage collection. If there is a lot of free memory, the Framework may defer garbage collection for some time.
|< Day Day Up >|