DynamicMethod is much slower than compiled IL function

后端 未结 2 1158
伪装坚强ぢ
伪装坚强ぢ 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:26

    This problem was introduced by changes made in .NET Framework 4.0. I found a solution posted by user "Alan-N" on CodeProject.

    The big slowdown in execution time is caused when the DynamicMethod gets associated with a "system-provided, fully trusted, security-transparent assembly," which happens if you use the DynamicMethod(string, Type, Type[], bool) constructor. It appears that .NET 4 is doing more security checks than the previous versions although I have no insight into, or explanation for, what is actually going on.

    Associating the DynamicMethod with a Type (by using the DynamicMethod(string, Type, Type[], Type, bool) constructor instead; notice the additional Type-valued parameter, 'owner') completely removes the speed penalty.

    There are some notes on MSDN which may be relevant (if only I could understand them!):

    • DynamicMethod Constructor (String, Type, Type[], Boolean)
    • Security Issues in Reflection Emit
    0 讨论(0)
  • 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<int,int> 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.

    0 讨论(0)
提交回复
热议问题