代表和结构的速度问题

时间:2011-11-10 09:19:01

标签: .net performance delegates struct

我遇到了一些关于结构和委托的速度问题 - 请使用以下控制台应用程序代码:

public delegate string StringGetter();
public class LocalString
{
    public LocalString(string value)
    {
        this.value = value;
    }

    public StringGetter Getter
    {
        get
        {
            return new StringGetter(this.GetValue);
        }
    }

    private string GetValue()
    {
        return value;
    }

    private string value;
}


class Program
{
    static void Main(string[] args)
    {
        var start = DateTime.Now;
        for (int i = 0; i < 2000000; i++)
        {
            var val = new LocalString( "hello World" );
            val.Getter();
        }
        Console.WriteLine((DateTime.Now - start).TotalMilliseconds);
        Console.ReadKey();
    }
}

在我的机器上执行时需要大约1.8秒...如果我将结构更改为类,它运行~0.1秒。我已经看了底层的汇编代码和开源ROTOR代码,看看为什么,并且有一些特殊代码用于具有struct目标的委托,我猜测它是用于处理函数MethodDesc * COMDelegate ::中的装箱和拆箱:: GetDelegateCtor(TypeHandle delegateType,MethodDesc * pTargetMethod,DelegateCtorArgs * pCtorData)。

另一点 - 如果您在VS2008中以.net 3.5为目标构建此应用程序,则运行速度比在VS2010中以.net 3.5为目标运行速度要快。我还没弄清楚为什么会这样。

欢迎任何评论/更好的启示......

此致 利

1 个答案:

答案 0 :(得分:3)

这很难准确回答,代表的CLR支持代码是一个难以破解的难题。我最好的猜测是un / box结构值所需的开销。委托调用是通过存根进行的,该存根首先对值进行处理,以便可以调用实例方法。调用之后,需要将方法的任何副作用复制回原始结构。与对引用类型的实例方法的简单调用相比,这是非常昂贵的,它们非常快。我没有看到任何验证结构值的活跃性的证据,有点奇怪,但可能在某处。