C# Dynamic Keyword — Run-time penalty?

后端 未结 6 1221
春和景丽
春和景丽 2020-12-01 14:20

Does defining an instance as dynamic in C# mean:

  1. The compiler does not perform compile-time type checking, but run-time checking takes place like it always

6条回答
  •  广开言路
    2020-12-01 15:00

    As far as I know, the answer is 3.

    You can do this:

    dynamic x = GetMysteriousObject();
    x.DoLaundry();
    

    Since the compiler does no type checking on x, it will compile this code, the assumption being that you know what you're doing.

    But this means extra run-time checking has to occur: namely, examining x's type, seeing if it has a DoLaundry method accepting no arguments, and executing it.

    In other words the above code is sort of like doing this (I'm not saying it's the same, just drawing a comparison):

    object x = GetMysteriousObject();
    
    MethodInfo doLaundry = x.GetType().GetMethod(
        "DoLaundry",
        BindingFlags.Instance | BindingFlags.Public
    );
    
    doLaundry.Invoke(x, null);
    

    This is definitely not trivial, though that isn't to say you're going to be able to see a performance issue with your naked eye.

    I believe the implementation of dynamic involves some pretty sweet behind-the-scenes caching that gets done for you, so that if you run this code again and x is the same type, it'll run a lot faster.

    Don't hold me to that, though. I don't have all that much experience with dynamic; this is merely how I understand it to work.

提交回复
热议问题