与代表和结构网速问题 [英] Speed Issues with delegates and Structs

查看:202
本文介绍了与代表和结构网速问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到的一些速度问题,关于结构和代表 - 采取以下控制台应用程序code:

I've run into some speed issues with regards to structs and delegates - take the following console application code:

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.1secs类。我有一个看下面的组装code和开源转子code看出为什么有一些特殊的$ C $下有一个结构的目标,我猜是委托办理拳击和拆箱函数方法描述* COMDelegate :: GetDelegateCtor(类型句柄delegateType,方法描述* p​​TargetMethod,DelegateCtorArgs * pCtorData)。

When executed on my machine it takes ~1.8 secs...If I change the struct to a class it runs in ~0.1secs. I've had a look at the underlying assembly code and open source ROTOR code to see why and there is some special code for delegates that have a struct target which I'm guessing is for handling boxing and unboxing in function MethodDesc* COMDelegate::GetDelegateCtor(TypeHandle delegateType, MethodDesc *pTargetMethod, DelegateCtorArgs *pCtorData).

还有一点 - 如果你在​​VS2008中建立这个目标.NET 3.5的应用程序运行,如果你运行它在VS2010针对.NET 3.5的速度比。我还没有想出这是为什么。

Another point - if you build this in VS2008 targeting .net 3.5 the app runs faster than if you run it in VS2010 targeting .net 3.5. I haven't figured out why this is.

任何意见/更好的启发将受到欢迎...

Any comments / better enlightenment would be welcome...

问候 李

推荐答案

这是很难准确回答,CLR的支持,code为代表是一个难啃的骨头。我最好的猜测是需要联合国/箱结构值的开销。委托呼叫通过一个存根第一盒值,因此实例方法可以调用进行。通话结束后,需要复制回原始结构的方法的任何副作用。 ,相比引用类型的实例方法简单的调用是昂贵的,他们的非常的快。我没有看到任何证据来验证结构值,有点奇怪的活跃度,但很可能会出现的地方。

This is hard to answer accurately, the CLR support code for delegates is a tough nut to crack. My best guess is the overhead required to un/box the struct value. The delegate call is made through a stub that first boxes the value so the instance method can be called. After the call, any side-effects of the method needs to be copied back to the original struct. That's expensive compared to a simple call to the instance method of a reference type, they are very fast. I didn't see any evidence for validating the liveness of the struct value, a bit odd, but might well be there somewhere.

这篇关于与代表和结构网速问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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