开发者

Does Properties increase memory size of Instances?

This is probably a stupid question, but does object Properties occupy any memory per instance?

As I've understand it when you instantiate an object each value field occupies its size and reference field types 4 bytes p开发者_如何转开发er field. But say you have an object with 1000 properties that fetches data via some other object, does those properties occupy any memory in themselves?

Automatic properties naturally does since it's just syntactic sugar but it doesn't seem like ordinary Properties should...


Properties are just like ordinary methods in that respect.

The code needs to be stored somewhere (once per Type) and any fields that are used (Auto properties!) need to be stored per instance. Local variables will also take up some memory.

Some examples:

private int myProperty;
public int MyProperty { get => myProperty; set => myProperty; }

The property itself doesn't take up instance memory, but myProperty of course does.

public int MyProperty { get; set; }

I didn't define any backing field, but the compiler did it for me - so that generated backing field still takes up instance memory.

public int Count => somelist.Count;

Here is no additional backing field, so this doesn't require any extra instance memory (except for someList of course).


Straight from Apress Illustrated C#

Unlike a field, however, a property is a function member.
- It does not allocate memory for data storage!


No, properties are just syntactic sugar for getter and setter methods. Only the backing fields occupy memory. If you have no backing fields, you will have no per-instance memory usage.


If you look at a compiled C# class through for instance reflector you will see that the compiler actually translates the properties into get and set methods, auto properties are translated into get and set methods with a backing field, so the field will take up as much room as a regular field


Properties are tranlated into two (or just one in case You provided only a getter or perhaps a setter) method that is

public int MyProp
{
    get { return 1; }
    set { myField = value; }
}

is translated during compilation (probably Eric Lipper will correct me on this, becasue maybe it is during the preprocessing phase or sth) into methods

public int Get_MyProp();
public int Set_MyProp(int value);

all in all they carry no other overhead other than just to additional methods inluced in the object

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜