bytefire bytefire - 3 years ago 213
C# Question

Is separate memory allocated for functions and properties of an object?

This question is about .NET but I think it applies generally. When a new object is instantiated, are the functions in that object allocated memory too? Even if they are not called till a later point?

Put differently, will two classes with same member variables but one with more methods inside it occupy more memory at the time of instantiation?

Answer Source

Object instance represents the state of the instance you allocated. So it holds a copy of all fields and properties you define inside corresponding type.

Methods that you define for a given type stay in another data structure, out from the instance itself, called Method Table. Every single instance you allocate has a pointer inside that points to the its type's Method Table.

enter image description here

When you call a function on the method, it shifts its pointer necessary amount of addresses, pull the function, push on the stack all arguments available in memory, and calls the function.

More on this can read here: Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download