When we declare a variable, does the variable itself consume memory?
class IHaveNothing
{
}
class IHaveNullFields
{
string @string = null;
StringBuilder @StringBuilder = null;
}
class Program
{
static void Main(string[] args)
{
IHaveNothing nothing = new IHaveNothing();
IHaveNullFields nullFields = new IHaveNullFields();
}
}
Does the instance nullFields consume more memories than the instance nothing ?
EDIT: How about null local variables as opposed to class' null fields, do they consume memory too?
A local variable occupies memory that the system allocates when it sees the variable's definition during execution. The system also deallocates that memory automatically at the end of the block that contains the definition.
A char variable normally uses 1 byte of memory.
When a variable is declared compiler automatically allocates memory for it. This is known as compile time memory allocation or static memory allocation. Memory can be allocated for data variables after the program begins execution.
No a constant uses the exact same memory. The only difference is that you can't change your constant after it's initialized.
Yes, they consume the pointer size of the machine (at least).
A variable is defined as a storage location. So the question is: does a storage location consume memory?
When you say it that way it sounds obvious that the answer is yes. What else would a storage location do other than consume memory?
It's not as simple as that. A local variable can consume no memory at all; a local variable might be enregistered by the jitter. In that case it would consume neither stack nor heap memory.
Why do you care? The way that the CLR manages memory to make storage locations for variables is an implementation detail. Unless you're writing unsafe code, you don't have to worry about it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With