tags:

views:

43

answers:

2

When a class is compiled in c# do the functions get stored with it, thus increasing the memory required?

In other words is it worth creating two classes 1 to store the data and one to store all the functions with an instance of the data class?

So if I have 200 instances of the data only class would it differ (memory required) from 200 instances of the data+function class?

+5  A: 

The functions are not stored with the instance of the class. The overhead of the functions is associated with the Type and not the individual instances. So the instance footprint is not affected by the number of functions.

Here is a link I found doing a quick 'Bing' that will provide more detail if you are interested. http://www.codeproject.com/KB/cs/net_type_internals.aspx

Chris Taylor
+2  A: 

When you instantiate a reference type the CLR will create a Type Object on the heap - all objects in the heap contain 2 overhead members, the type object pointer and the sync block index. Any methods are entered into the types' Method Table, with one enty per method defined within the type.

So, whenever a new object is created, the CLR will automatically initialize the internal type object pointer (of this new object) to point to the actual Type Object - of which there is only one per reference type (sorry about the over use of the word 'type').

The first time a method is called, the CLR follows the type object pointer to the actual Type and the method is JITed, the CLR then calls this code, for subsequent method calls the CLR will call the already JIT'd code that is associated with the Type - as opposed to the object itself.

So, the functions/methods themselves are within the type not the actual object that you have created.

Happy to stand corrected on the finer points of this if anyone has any observations....

jameschinnock