DynamicMethod is much slower than compiled IL function

后端 未结 2 1171
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 23:56

I wrote a simple object copier that copies public properties. I can\'t figure out why the Dynamic method is a lot slower than the c# version.

Durations

C# me

2条回答
  •  [愿得一人]
    2020-12-24 00:30

    This is a bit late, but if you set a few security attributes in .NET 4 on all your assemblies and you use built-in delegate types—or delegates with the same security attributes—you will see quite a performance gain.

    Here are the attributes you will want:

    [assembly: AllowPartiallyTrustedCallers]
    [assembly: SecurityTransparent]
    [assembly: SecurityRules(SecurityRuleSet.Level2,SkipVerificationInFullTrust=true)]
    

    This actually seems to be a bit of a bug. But because you are saying that your code will not raise security permissions, you will not block partially-trusted callers, so if you use skipVisibility=true in full trust, invoking a Func delegate should basically avoid almost all of the permission checks.

    One more thing, since these are delegates you will get the best performance if you treat them like instance methods, even though they are not. That is to say always use one of the two Delegate.CreateDelegate methods that accepts a firstArgument parameter and add an initial object reference to your delegate.

    Consider constructing the DynamicMethod with skipVisibility=true, but without assigning an owner. Assigning an owner allows you to run unverifiable code. You can do some really screwed up things with this, so I would avoid it unless you know what you are doing.

提交回复
热议问题