Wendi
Wendi

Reputation: 140

Is an empty variable has same size as filled variable in C#

This is fundamental question, I need to suppress memory use of my code in C#. I wonder if I initiate class A (let's say it have 10 variables) and I fill all variables with values. In another case I initiate class A and I fill only 2 variables with values, and let the rest is null or empty if it's a string. Will the first case has the higher memory consumptioon?

Upvotes: 1

Views: 932

Answers (2)

kkica
kkica

Reputation: 4104

Probably. If a property of your class is a reference type, then if you assign to this property you will have some memory assigned because of that property. Example:

class House{
   object TV {get; set;}
}

If you do var house= new House(); you will use the space of house reference and Tv reference. However if you do this:

var house= new House() {
    TV= new {height= 100, width=1000}
};

it will take more since now the TV object takes space in addition to the TV reference. So you will have used extra space for height and width.

If you have a simple value type as a property:

class House{
       int Price {get; set;}
    }

It will not make any difference with

var house = new House(); 

or

var house = new House(){ Price=20000 };

That is because Price will be set to the int default value( which is 0), and every int takes the same space regardless of its value.

Upvotes: 1

user12031933
user12031933

Reputation:

Yes, an empty variable has same size as filled variable in C# if variable is a value type or a reference: it takes the same memory space.

For example an int takes 4 bytes and long takes 8 bytes.

It the same for references, assigned or not.

A reference on x32 takes 4 bytes but in x64 it takes 8 bytes.

Each value type takes the size of the value with added the size of the hidden hidden pointer (the hidden reference).

When it is not the same size is for all types based on arrays like value[] and strings: in this case the initial size is the pointer size and then the space grows as the data is populated.

Hence the memory size of an array of int grows as you add integers, and it is the same as a string grows.

It is because it is sometimes preferable to use a StringBuilder instead of a String, and to avoid the use of ToList() for example when useless.

To this must be added the references of the methods and the virtual tables.

You can get the size of a serializable instance, excluding the reference and the methods tables, using:

using System.Runtime.Serialization.Formatters.Binary;

static public long SizeOf(object obj)
{
  if ( obj == null ) return 0;
  try
  {
    using ( MemoryStream stream = new MemoryStream() )
    {
      new BinaryFormatter().Serialize(stream, obj);
      return stream.Length;
    }
  }
  catch 
  { 
    return -1; 
  }
}

Upvotes: 0

Related Questions