DynamicMethod is much slower than compiled IL function

醉酒当歌 提交于 2019-11-29 22:41:20
Michael B

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.

Pascal Ganaye

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!):

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!