Does DynamicMethod 'skipVisibility' have a performance penalty?

263 Views Asked by At

When creating a DynamicMethod in C# for which bypassing visibility is not necessary or irrelevant, what is the best value to specify for the skipVisibility parameter of the DynamicMethod constructor? Is there a performance penalty, i.e., associated with a runtime security demand, for specifying true for the skipVisibility, and if so, would the penalty occur on every call, or just once at JIT-time, prior to first access?

MSDN doc: DynamicMethod

1

There are 1 best solutions below

0
Glenn Slayden On

I found some relevant code in the .NET reference source for DynamicMethod. As shown below, specifying skipVisibility forces a security demand for ReflectionPermission. (The code also has another case where this permission is demanded regardless of the skipVisibility parameter).

[SecurityCritical]
private void PerformSecurityCheck(Type owner, ref StackCrawlMark stackMark, bool skipVisibility)
{
    if (owner == null)
        throw new ArgumentNullException("owner");

    RuntimeType underlyingSystemType = owner as RuntimeType;
    if (underlyingSystemType == null)
        underlyingSystemType = owner.UnderlyingSystemType as RuntimeType;

    if (underlyingSystemType == null)
        throw new ArgumentNullException("owner", Environment.GetResourceString("Argument_MustBeRuntimeType"));

    RuntimeType callerType = RuntimeMethodHandle.GetCallerType(ref stackMark);
    if (skipVisibility)
        new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
    else if (callerType != underlyingSystemType)
        new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();

    this.m_creatorAssembly = callerType.GetRuntimeAssembly();
    if (underlyingSystemType.Assembly != this.m_creatorAssembly)
        CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence, owner.Assembly.PermissionSet);
}

So an answer would be that there may be a performance penalty when specifying true for skipVisibility. However, depending on the various other argument types you use with new DynamicMethod(...) and perhaps the IL that you emit, your DynamicMethod may actually require ReflectionPermission, and you will not be able to specify false. The error given in such cases is:

System.TypeAccessException: Attempt by security transparent method 'DynamicClass.foo(MyType,int)' to access security critical type 'MyType' failed.