简体   繁体   中英

When will the memory be allocated for the variables, at declaration or at initialization?

Consider two cases in C#

Case-1

int a;
a = 10;

Where and when will the memory be allocated for a ?

Case-2

int a = 10;

What is the difference between these two cases and how will they vary in terms of memory allocation?

Local variables are allocated on the call stack at the moment that the prologue code is executed. So before your function even gets called 4 bytes are reserved in the current stack frame for the int variable (and any parameters). That memory is gone when the stack frame gets wiped which is what happens when the function call ends. This is the same behavior you'll see in any stack-based programming language (for the most part). For general questions like this your best bet is to use google to search for how things work.

The only time extra memory is allocated is when you use new. At the point of using new then the memory is allocated in the heap and a reference returned to your local variable (which was allocated at the point of function call).

So, in response to your question, it depends.

Local variables/parameters - during function prologue code Ref instances - at the point you call new Fields in types - at the point the instance of the type is created (via new) Initialization is a completely separate process. The ref instance bears closer discussion. Given the following code there are 2 allocations.

MyClass instance = new MyClass();

The first allocation is for the local variable instance. As a ref variable it takes up 4/8 bytes on the stack. The second allocation occurs at the moment new is executed. Space in the heap is allocated for MyClass and you get back a reference which is then assigned to your (already allocated) local variable.

When the function call ends the instance variable is wiped (because the stack frame is gone) while the instance of MyClass will hang around until the GC runs to clean it up.

Memory is allocated when a variable is declared, not when it's initialized. So in the first example the memory will be allocated when the first line is reached, and in the second example, well, the declaration and initialization are on the same line, so obviously the memory will be allocated then.

Edit: When you declare a reference-type local variable, memory on the stack is allocated for the reference. When you initialize that variable, then memory on the heap is allocated for the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM