Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 per 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...

like image 570
Homde Avatar asked Nov 19 '10 09:11

Homde


2 Answers

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).

like image 99
Hans Kesting Avatar answered Sep 30 '22 14:09

Hans Kesting


Straight from Apress Illustrated C#

Unlike a field, however, a property is a function member.
- It does not allocate memory for data storage!
like image 36
Marko Avatar answered Sep 30 '22 14:09

Marko