Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance considerations of inheritance in C#

Does the compiler produce the same IL if I make a class with public int I; (or any other field) vs making a class that inherits from a base class that has public int I;?

Either way the resulting class behaves identically, but does the compiler behave identically?

I.e., is the compiler just copy-pasting code from base classes into the derived classes, or is it actually creating two different class objects when you inherit?

class A
{
    public int I;
}

class B : A
{
}

Now is there any performance difference between the following two DoSomething() calls?

var a = new A();
var b = new B();
DoSomething(a.I);
DoSomething(b.I); // Is this line slower than the above line due to inheritance?

Try to ignore any optimizations the compiler might do for this special case. My question is about whether inheritance in C# in general has an associated performance penalty. Most of the time I don't care, but sometimes I want to optimize a piece of high frequency code.

like image 698
Olhovsky Avatar asked May 06 '11 05:05

Olhovsky


People also ask

What are the advantages of using inheritance?

Benefits of Inheritance Inheritance helps in code reuse. The child class may use the code defined in the parent class without re-writing it. Inheritance can save time and effort as the main code need not be written again. Inheritance provides a clear model structure which is easy to understand.

Does C language support inheritance?

No, it doesn't. Show activity on this post. There is no Compiler-level support for inheritance in C. Nevertheless, as others have already pointed out, Object Oriented coding does not REQUIRE such support.

What is inheritance in C with example?

Inheritance is one of four pillars of Object-Oriented Programming (OOPs). It is a feature that enables a class to acquire properties and characteristics of another class. Inheritance allows you to reuse your code since the derived class or the child class can reuse the members of the base class by inheriting them.


1 Answers

What the compiler emits is identical; indeed, even when calling a non-virtual instance method on a sealed class it uses Callvirt - which is the same as it would use calling any method with polymorphism.

And no: it isn't copy/paste - the code you wrote in A remains as part of A. And no, you don't get 2 objects just because of inheritance. It is combining the behaviour; an instance of B also has the implementation from A - but not via copy paste: a B is also an A - i.e. a Dog is also a Mammal, etc.

like image 113
Marc Gravell Avatar answered Oct 03 '22 06:10

Marc Gravell