In C#, do objects which have a local scope use the stack?
Say we have
void Foo() {
var bar = new Bar();
bar.Woo();
}
Will the CLR use the stack for the local variable?
If not, why? Is it not more efficient to use the stack for variables which have a limited scope instead of using a more expensive garbage collector?
Not only the CLR would need to know that the scope is local, but also that the object wont be referenced from anywhere else. This would need a deep code analysis except for the most trivial cases, like the one you posted.
In theory, some type of escape analysis could be performed by the CLR. If that led to the conclusion that the object was only accessible from the local context, it could then go ahead and allocate the object on the stack. At this point, however, that is not done, and a class will always be allocated in the long-term storage area (aka "the heap".)
Also, note that the variable bar
is allocated on the stack (or possibly enregistered). It contains a reference to the newly created Bar
object (on the heap), and will disappear when the method exits.
the Value Type is on stack and for Reference type the reference(the things like pointer) is on stack but the object is on managed heap
refer to C# Concepts: Value vs Reference Types http://www.albahari.com/valuevsreftypes.aspx
链接地址: http://www.djcxy.com/p/78904.html