C#中继承的性能注意事项 [英] Performance considerations of inheritance in C#

查看:186
本文介绍了C#中继承的性能注意事项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用public int I;(或任何其他字段)创建类,而不是使用从具有public int I;的基类继承的类,则编译器会产生相同的IL吗?

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
{
}

现在以下两个DoSomething()调用之间是否存在性能差异?

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?

尝试忽略编译器针对此特殊情况可能执行的任何优化.我的问题是有关C#中的继承是否总体上具有相关的性能损失.大多数时候我不在乎,但有时我想优化一段高频代码.

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.

推荐答案

编译器发出的内容是相同的.实际上,即使在密封类上调用非虚拟实例方法时,它也会使用Callvirt-与使用任何具有多态性的方法相同.

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.

而且不是:它不是复制/粘贴-您在A中编写的代码仍作为A的一部分.不,您不会因为继承而获得2个对象.它结合了行为B的一个实例也具有A的实现,但不是通过复制粘贴实现的:B 也是 的一个A-即Dog也是Mammal,依此类推.

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.

这篇关于C#中继承的性能注意事项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆