摘自:《Oreilly Programming Fsharp》Chapter 4 Imperative Programming
Understanding Memory in .NET
Before you can start making changes to memory, you first need to understand how
memory works in .NET. Values in .NET applications are stored in one of two locations:
on the stack or in the heap. (Experienced programmers may already be familiar with
these concepts.) The stack is a fixed amount of memory for each process where local
variables are stored. Local variables are temporary values used only for the duration of
the function, like a loop counter. The stack is relatively limited in space, while the heap
(also called RAM) may contain several gigabytes of data. .NET uses both the stack and
the heap to take advantage of the cheap memory allocations on the stack when possible,
and store data on the heap when more memory is required.
The area in memory where a value is stored affects how you can use it.
Value Types Versus Reference Types
Values stored on the stack are known as value types, and values stored on the heap are
known as reference types.
Value types have a fixed size of bytes on the stack. int and float are both examples of
value types, because their size is constant. Reference types, on the other hand, only
store a pointer on the stack, which is the address of some blob of memory on the heap.
So while the pointer has a fixed size—typically four or eight bytes—the blob of memory
it points to can be much larger. list and string are both examples of reference types.
This is visualized in Figure 4-1. The integer 5 exists on the stack, and has no counterpart
on the heap. A string, however, exists on the stack as a memory address, pointing to
some sequence of characters on the heap.