Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (19.33 KB, 3 trang )
How Computer Memory is Organized
Computers use memory to hold programs being executed, and the data that these
programs use. In order to understand the differences between value and reference types, it
is helpful to understand how data is organized in memory.
Operating systems and runtimes (such as the common language runtime) frequently
divide the memory used for holding data into two separate chunks, each of which is
managed in a distinct manner. These two chunks of memory are traditionally called the
stack and the heap. The stack and the heap serve very different purposes:
• When you call a method, the memory required for its parameters and its local
variables is always acquired from the stack. When the method finishes (because it
either returns or throws an exception), the memory acquired for the parameters
and local variables is automatically released back to the stack and is available for
reuse when another method is called.
• When you create an object (an instance of a class) by using the new keyword and a
constructor call, the memory required to build the object is always acquired from
the heap. You have seen that the same object can be referenced from several
places by using reference variables. When the last reference to an object
disappears, the memory used by the object becomes available for reuse (although
it might not be reclaimed immediately). Chapter 13 includes a more detailed
discussion of how heap memory is reclaimed.
NOTE
All value types are created on the stack. All reference types (objects) are created
on the heap.
The names stack and heap come from the way in which the runtime organizes memory:
• Stack memory is organized like a stack of boxes piled on top of each other. When
a method is called, each parameter is put in a box which is placed on top of the
stack. Each local variable is likewise assigned a box, and these are placed on top
of the boxes already on the stack. When a method finishes, all its boxes are
removed from the stack.