Search code examples
c#memory-managementclr

Effect of properties or get/set methods on object size


In terms of object size, how do properties instead Get/Set methods affect object size if the exposed properties do not represent a state but simply delegate its getter and setter calls to another entity?

For example, consider the following classes:

public class Person
{
   Address _address = new Address();

   public string AddressName
   {
      get{ return _address.Name; }
      set { _address.Name = value; }
   }

   public string GetAddressName(){ return _address.Name; }
   public void SetAddressName(string name){ _address.Name = name; }

}

public Address
{
    public string Name { get; set; }
}

I am guessing that when a new Person is created, the CLR will take into consideration the potential size of AddressName property when determining how much memory to allocate. However, if all I exposed was the Get/Set AddressName methods, there will be no additional memory allocated to cater for an AddressName property. So, to conserve memory footprint, it is better in this case to use Get/Set methods. However, this will not make a difference with the Name property of the Address class as state is being preserved. Is this assumption correct?


Solution

  • The size of an individual object is not affected by the number of properties, methods, events etc. It affects the size of the type metadata, and the JITted code - but not the per-object size. That's only affected by instance fields.

    I am guessing that when a new Person is created, the CLR will take into consideration the potential size of AddressName property when determining how much memory to allocate.

    No. It only looks at your fields. You have a single field (_address) so that plus the normal object overhead are all the memory required for a single instance.