views:

241

answers:

2

In C# (.NET) how exactly methods (virtual, static, non-virtual) impact on class size?

+6  A: 

Each method takes memory to hold its byte code. The code exists once for each method¹, not once for each instance.

Adding and removing instance methods (virtual or non-virtual) won't change the size of your allocated objects. This is not like C++, where adding virtual methods sometimes does increase the size of your allocated objects. Like C++, static methods won't change the size of your allocated objects.

¹ For generic methods, one copy exists for each set of type(s) it's instantiated with.

Edit: In response to the comments, I'll go into more detail.

@Richard: that may or may not be true (it can vary). Only one copy of the IL byte code is ever needed. One method descriptor block is needed for the open constructed method and closed constructed method, plus descriptors for constructed instances that still contain generic type parameters (method with generic arguments in a generic-parameterized base type of a generic type definition). Generally one copy of the native code would be kept for each closed constructed instance that's a value type plus one for zero or more reference types, but there could be zero (not JIT'd/just interpreted) or two or more (baseline and optimizing compiler, where one or more callstacks haven't left the baseline version since the method was recompiled with the optimizing JIT). Edit again: You are correct in that the generic parameter constraints allow just one copy of the native code for all reference types it's instantiated with.

280Z28
Thanks, that's what I'm looking for. Can you give any official references?
aloneguid
For generic methods with a single type parameter, one copy exists for each value type the generic type is instantiated over and once for all reference types together (or zero, if not instantiated over any reference types). Expand for each combination of multiple type parameters...
Richard
I think he's asking for instance size, not total code size.
Barry Kelly
+1  A: 

The per-instance size depends on the fields of the class, not the methods. Depending on the implementation details, implementing an interface may take up space in the instance (possibly one pointer-sized slot per interface), but it is not guaranteed to do so.

You'll have a hard time finding "official references" for implementation-defined behaviour, though, as it may change in the future.

Barry Kelly