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.
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>andList<Stream>share native code, butList<int>andList<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.