Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# class code loaded in RAM?

I would like to know whether the actual code of a C# class gets loaded in RAM when you instantiate the class?

So for example if I have 2 Classes CLASS A , CLASS B, where class A has 10000 lines of code but just 1 field, an int. And class B has 10 lines of code and also 1 field an int as well. If I instantiate Class A will it take more RAM than Class B due to its lines of code ?

A supplementary question, If the lines of code are loaded in memory together with the class, will they be loaded for every instance of the class? or just once for all the instances?

Thanks in advance.

like image 330
PB_MLT Avatar asked Dec 10 '22 17:12

PB_MLT


2 Answers

In the desktop framework, I believe methods are JITted on a method-by-method basis. I don't know whether the IL for a class is completely loaded into RAM when the class is first loaded, or whether they're just memory mapped to the assembly file.

Either way, you get a single copy for all instances - at least for non-generic types. For generic types (and methods) it gets slightly more complicated - there's one JIT representation for all reference type type arguments, and one for each value type type argument. So List<string> and List<Stream> share native code, but List<int> and List<Guid> don't. (Extrapolate as appropriate for types with more than one generic type parameter.) You still only get one copy for all instances of the same constructed type though - objects don't come with their own copy of the native code.

like image 147
Jon Skeet Avatar answered Dec 23 '22 12:12

Jon Skeet


An instance of type A will take exactly the same amount of memory as type B. The amount of memory used by an instance of a type is a direct result of the fields which it contains so if both types contain the same fields, then instances of both types will contain the same amount of memory. Of course, if you have variable length fields, such as strings, arrays, collections etc. then you have to take this into account, but if the fields are set to the same values for each type then the same amount of memory will be used.

Within an app domain, the code containing the instructions for the methods of each type will only be loaded once, rather than for each instance of the type. As Jon says, it is important to remember that each closed generic type (with all type parameters stated) is a separate runtime type.

Incidentally, it is not important how many lines of source code your type contains, but how much IL this source code compiles to. However, if one type has 10 line of source code and another has 10,000 then it is highly likely that the IL for that latter class will be much greater. You can examine the IL by using a tool such as .NET Reflector.

like image 44
Adam Ralph Avatar answered Dec 23 '22 13:12

Adam Ralph