Memory allocation: Stack vs Heap?
m
is allocated on the heap, and that includes myInt
. The situations where primitive types (and structs) are allocated on the stack is during method invocation, which allocates room for local variables on the stack (because it's faster). For example:
class MyClass
{
int myInt = 0;
string myString = "Something";
void Foo(int x, int y) {
int rv = x + y + myInt;
myInt = 2^rv;
}
}
rv
, x
, y
will all be on the stack. myInt
is somewhere on the heap (and must be access via the this
pointer).
You should consider the question of where objects get allocated as an implementation detail. It does not matter to you exactly where the bits of an object are stored. It may matter whether an object is a reference type or a value type, but you don't have to worry about where it will be stored until you start having to optimize garbage collection behavior.
While reference types are always allocated on the heap in current implementations, value types may be allocated on the stack -- but aren't necessarily. A value type is only allocated on the stack when it is an unboxed non-escaping local or temporary variable that is not contained within a reference type and not allocated in a register.
- If a value type is part of a class (as in your example), it will end up on the heap.
- If it's boxed, it will end up on the heap.
- If it's in an array, it will end up on the heap.
- If it's a static variable, it will end up on the heap.
- If it's captured by a closure, it will end up on the heap.
- If it's used in an iterator or async block, it will end up on the heap.
- If it's created by unsafe or unmanaged code, it could be allocated in any type of data structure (not necessarily a stack or a heap).
Is there anything I missed?
Of course, I would be remiss if I didn't link to Eric Lippert's posts on the topic:
- The Stack Is An Implementation Detail, Part One
- The Stack Is An Implementation Detail, Part Two
- And perhaps the best one: The Truth About Value Types