Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a variable itself consume memory?

Tags:

c#

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?

like image 516
xport Avatar asked Jul 31 '10 14:07

xport


People also ask

Do variables occupy memory?

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.

How much memory does a variable take?

A char variable normally uses 1 byte of memory.

Is memory allocated when a variable is declared?

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.

Do constants use less memory?

No a constant uses the exact same memory. The only difference is that you can't change your constant after it's initialized.


2 Answers

Yes, they consume the pointer size of the machine (at least).

like image 116
Tassos Bassoukos Avatar answered Sep 21 '22 09:09

Tassos Bassoukos


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.

like image 44
Eric Lippert Avatar answered Sep 23 '22 09:09

Eric Lippert