不要在C#泛型接口防止拳? (.NET VS黑白性能) [英] Do generic interfaces in C# prevent boxing? (.NET vs Mono performance)

查看:103
本文介绍了不要在C#泛型接口防止拳? (.NET VS黑白性能)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个声明为对象类型的某些方法参数一个C#接口。不过,传来传去的实际类型可以根据类实现接口不同:

I have a C# interface with certain method parameters declared as object types. However, the actual type passed around can differ depending on the class implementing the interface:

public interface IMyInterface
{
    void MyMethod(object arg);
}

public class MyClass1 : IMyInterface
{
    public void MyMethod(object arg)
    {
        MyObject obj = (MyObject) arg;
        // do something with obj...
    }
}

public class MyClass2 : IMyInterface
{
    public void MyMethod(object arg)
    {
        byte[] obj = (byte[]) arg;
        // do something with obj...
    }
}



的东西

与MyClass2的问题是,转换的byte [] 和从对象是的装箱和拆箱,这是计算影响性能昂贵的操作。

The problem with MyClass2 is that the conversion of byte[] to and from object is boxing and unboxing, which are computationally expensive operations affecting performance.

会解决这个问题href=\"http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx\" rel=\"nofollow\">通用接口一个

Would solving this problem with a generic interface avoid boxing/unboxing?

public interface IMyInterface<T>
{
    void MyMethod(T arg);
}

public class MyClass1 : IMyInterface<MyObject>
{
    public void MyMethod(MyObject arg)
    {
        // typecast no longer necessary
        //MyObject obj = (MyObject) arg;
        // do something with arg...
    }
}

public class MyClass2 : IMyInterface<byte[]>
{
    public void MyMethod(byte[] arg)
    {
        // typecast no longer necessary
        //byte[] obj = (byte[]) arg;
        // do something with arg...
    }
}



的东西

这是如何在.NET中实现单VS?会有两种平台上的任何性能影响?

How is this implemented in .NET vs Mono? Will there be any performance implications on either platform?

感谢您!

推荐答案

我不知道它是如何在单声道实现,但通用接口会帮助,因为编译器创建的具体类型,所使用的每个不同类型的(内部,也有少数情况下,它可以利用相同的新功能生成的函数)。如果产生的特定类型的功能,就没有必要到框/拆箱类型。

I'm not sure how it is implemented in mono, but generic interfaces will help because the compiler creates a new function of the specific type for each different type used (internally, there are a few cases where it can utilize the same generated function). If a function of the specific type is generated, there is no need to box/unbox the type.

这就是为什么Collections.Generic库是一个很大的打击在.NET 2.0,因为收藏品不再需要拳,成为显著更有效。

This is why the Collections.Generic library was a big hit at .NET 2.0 because collections no longer required boxing and became significantly more efficient.

这篇关于不要在C#泛型接口防止拳? (.NET VS黑白性能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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