Dynamic Lang. Runtime vs Reflection
Asked Answered
D

6

41

I am planning to use dynamic keyword for my new project. But before stepping in, I would like to know about the pros and cons in using dynamic keyword over Reflection.

Following where the pros, I could find in respect to dynamic keyword:

  • Readable\Maintainable code.
  • Fewer lines of code.

While the negatives associated with using dynamic keyword, I came to hear was like:

  • Affects application performance.
  • Dynamic keyword is internally a wrapper of Reflection.
  • Dynamic typing might turn into breeding ground for hard to find bugs.
  • Affects interoperability with previous .NET versions.

Please help me on whether the pros and cons I came across are sensible or not?

Dumbbell answered 10/1, 2011 at 12:26 Comment(2)
Do you need to do private reflection?Proulx
No I don't need to private reflection. What ever methods I need to call are always public.Dumbbell
S
27

Readable\Maintainable code

Certainly true in my experence.

Fewer lines of code.

Not significantly, but it will help.

Affects application performance.

Very slightly. But not even close to the way reflection does.

Dynamic keyword is internally a wrapper of Reflection.

Completely untrue. The dynamic keyword leverages the Dynamic Library Runtime.

[Edit: correction as per comment below]

It would seem that the Dynamic Language Runtime does use Reflection and the performance improvements are only due to cacheing techniques.

Dynamic typing might turn into breeding ground for hard to find bugs.

This may be true; it depends how you write your code. You are effectively removing compiler checking from your code. If your test coverage is good, this probably won't matter; if not then I suspect you will run into problems.

Affects interoperability with previous .NET versions

Not true. I mean you won't be able to compile your code against older versions, but if you want to do that then you should use the old versions as a base and up-compile it rather than the other way around. But if you want to use a .NET 2 library then you shouldn't run into too many problems, as long as you include the declaration in app.config / web.config.

One significant pro that you're missing is the improved interoperability with COM/ATL components.

Sugared answered 10/1, 2011 at 12:52 Comment(5)
So I can take your word that, there wont be any noticeable performance differences using dynamic (DLR) over reflection. Thanks for pointing out the improved interoperability on COM\ATL.Dumbbell
@Dumbbell - using dynamic is faster than using reflection, particularly if a method is called repeatedly (because of cacheing).Sugared
Re "Completely untrue. The dynamic keyword leverages the Dynamic Runtime Library." How exactly do you suppose the DLR does it? What magic does it have at its disposal whereby it can do runtime type analysis without reflection? The DLR doesn't have any magic; it uses Reflection when it needs to like any other code. It is just very clever about caching the result, but believe me, it uses reflection.Proulx
@Eric Lippert - I stand corrected. I understood it was a bit more complex than thatSugared
It is a lot more complex than that! Not all of the DLR analysis providers use reflection, but the C# one certainly uses reflection extensively to perform the runtime type analysis. And even though the result is cached, the runtime types that are the cache keys are always determined via reflection.Proulx
P
107

Please help me on whether the pros and cons I came across are sensible or not?

The concern I have with your pros and cons is that some of them do not address differences between using reflection and using dynamic. That dynamic typing makes for bugs that are not caught until runtime is true of any dynamic typing system. Reflection code is just as likely to have a bug as code that uses the dynamic type.

Rather than thinking of it in terms of pros and cons, think about it in more neutral terms. The question I'd ask is "What are the differences between using Reflection and using the dynamic type?"

First: with Reflection you get exactly what you asked for. With dynamic, you get what the C# compiler would have done had it been given the type information at compile time. Those are potentially two completely different things. If you have a MethodInfo to a particular method, and you invoke that method with a particular argument, then that is the method that gets invoked, period. If you use "dynamic", then you are asking the DLR to work out at runtime what the C# compiler's opinion is about which is the right method to call. The C# compiler might pick a method different than the one you actually wanted.

Second: with Reflection you can (if your code is granted suitably high levels of trust) do private reflection. You can invoke private methods, read private fields, and so on. Whether doing so is a good idea, I don't know. It certainly seems dangerous and foolish to me, but I don't know what your application is. With dynamic, you get the behaviour that you'd get from the C# compiler; private methods and fields are not visible.

Third: with Reflection, the code you write looks like a mechanism. It looks like you are loading a metadata source, extracting some types, extracting some method infos, and invoking methods on receiver objects through the method info. Every step of the way looks like the operation of a mechanism. With dynamic, every step of the way looks like business logic. You invoke a method on a receiver the same way as you'd do it in any other code. What is important? In some code, the mechanism is actually the most important thing. In some code, the business logic that the mechanism implements is the most important thing. Choose the technique that emphasises the right level of abstraction.

Fourth: the performance costs are different. With Reflection you do not get any cached behaviour, which means that operations are generally slower, but there is no memory cost for maintaining the cache and every operation is roughly the same cost. With the DLR, the first operation is very slow indeed as it does a huge amount of analysis, but the analysis is cached and reused. That consumes memory, in exchange for increased speed in subsequent calls in some scenarios. What the right balance of speed and memory usage is for your application, I don't know.

Proulx answered 10/1, 2011 at 17:32 Comment(2)
Thanks for the detailed analysis to my query. It was nice to know that DLR caches the analysis results.Dumbbell
This is by far the best answer to this questionTerrance
S
27

Readable\Maintainable code

Certainly true in my experence.

Fewer lines of code.

Not significantly, but it will help.

Affects application performance.

Very slightly. But not even close to the way reflection does.

Dynamic keyword is internally a wrapper of Reflection.

Completely untrue. The dynamic keyword leverages the Dynamic Library Runtime.

[Edit: correction as per comment below]

It would seem that the Dynamic Language Runtime does use Reflection and the performance improvements are only due to cacheing techniques.

Dynamic typing might turn into breeding ground for hard to find bugs.

This may be true; it depends how you write your code. You are effectively removing compiler checking from your code. If your test coverage is good, this probably won't matter; if not then I suspect you will run into problems.

Affects interoperability with previous .NET versions

Not true. I mean you won't be able to compile your code against older versions, but if you want to do that then you should use the old versions as a base and up-compile it rather than the other way around. But if you want to use a .NET 2 library then you shouldn't run into too many problems, as long as you include the declaration in app.config / web.config.

One significant pro that you're missing is the improved interoperability with COM/ATL components.

Sugared answered 10/1, 2011 at 12:52 Comment(5)
So I can take your word that, there wont be any noticeable performance differences using dynamic (DLR) over reflection. Thanks for pointing out the improved interoperability on COM\ATL.Dumbbell
@Dumbbell - using dynamic is faster than using reflection, particularly if a method is called repeatedly (because of cacheing).Sugared
Re "Completely untrue. The dynamic keyword leverages the Dynamic Runtime Library." How exactly do you suppose the DLR does it? What magic does it have at its disposal whereby it can do runtime type analysis without reflection? The DLR doesn't have any magic; it uses Reflection when it needs to like any other code. It is just very clever about caching the result, but believe me, it uses reflection.Proulx
@Eric Lippert - I stand corrected. I understood it was a bit more complex than thatSugared
It is a lot more complex than that! Not all of the DLR analysis providers use reflection, but the C# one certainly uses reflection extensively to perform the runtime type analysis. And even though the result is cached, the runtime types that are the cache keys are always determined via reflection.Proulx
B
16

There are 4 great differences between Dynamic and reflection. Below is a detailed explanation of the same. Reference http://www.codeproject.com/Articles/593881/What-is-the-difference-between-Reflection-and-Dyna

Point 1. Inspect VS Invoke

Reflection can do two things one is it can inspect meta-data and second it also has the ability to invoke methods on runtime.While in Dynamic we can only invoke methods. So if i am creating software's like visual studio IDE then reflection is the way to go. If i just want dynamic invocation from the my c# code, dynamic is the best option.

DynamicVsReflection

Point 2. Private Vs Public Invoke

You can not invoke private methods using dynamic. In reflection its possible to invoke private methods.

Point 3. Caching

Dynamic uses reflection internally and it also adds caching benefits. So if you want to just invoke a object dynamically then Dynamic is the best as you get performance benefits.

Point 4. Static classes

Dynamic is instance specific: You don't have access to static members; you have to use Reflection in those scenarios.

Benadryl answered 21/5, 2013 at 23:24 Comment(0)
T
4

In most cases, using the dynamic keyword will not result in meaningfully shorter code. In some cases it will; that depends on the provider and as such it's an important distinction. You should probably never use the dynamic keyword to access plain CLR objects; the benefit there is too small.

The dynamic keyword undermines automatic refactoring tools and makes high-coverage unit tests more important; after all, the compiler isn't checking much of anything when you use it. That's not as much of an issue when you're interoperating with a very stable or inherently dynamically typed API, but it's particularly nasty if you use keyword dynamic to access a library whose API might change in the future (such as any code you yourself write).

Use the keyword sparingly, where it makes sense, and make sure such code has ample unit tests. Don't use it where it's not needed or where type inference (e.g. var) can do the same.

Edit: You mention below that you're doing this for plug-ins. The Managed Extensibility Framework was designed with this in mind - it may be a better option that keyword dynamic and reflection.

Tong answered 10/1, 2011 at 12:37 Comment(6)
@Eamon: As mentioned I am not using dynamic keyword to access the plain CLR objects, instead the application which I had mentioned, provides plug-in model to handle new functionalities, because of this reflection is used extensively. To make this module effective and maintainable I was confused on whether to go for Reflection or for Dynamic keyword. The main concern for me is performance.Dumbbell
@Dumbbell Is your plugin model supported via interfaces, or by convention? If it is supported using interfaces, then little reflection needs to be used anyway.Kerosene
plugins should not require dynamic typing. Whether there's a performance issue really depends on what you're doing (millions of small calls vs. one or two big ones), but a priori I wouldn't expect performance to be an issue.Tong
Have you considered the Managed Extensibility Framework?Tong
@Eamon: For the plug-in model we are using interfaces, while XML files are used to handle some exceptional cases. Calling methods defined in the XML file is the complex part. We dynamically creates delegates to build the function container.Dumbbell
@Eamon: Thanks for pointing out the Managed Extensibility Framework, I will be definitely looking into that.Dumbbell
D
2

If you are using dynamic specifically to do reflection your only concern is compatibility with previous versions. Otherwise it wins over reflection because it is more readable and shorter. You will lose strong typing and (some) performance from the very use of reflection anyway.

Divorcement answered 10/1, 2011 at 13:8 Comment(0)
P
1

The way I see it all your cons for using dynamic except interoperability with older .NET versions are also present when using Reflection:

Affects application performance

While it does affect the performance, so does using Reflection. From what I remember the DLR more or less uses Reflection the first time you access a method/property of your dynamic object for a given type and caches the type/access target pair so that later access is just a lookup in the cache making it faster then Reflection

Dynamic keyword is internally a wrapper of Reflection

Even if it was true (see above), how would that be a negative point? Whether or not it does wrap Reflection shouldn't influence your application in any significant matter.

Dynamic typing might turn into breeding ground for hard to find bugs

While this is true, as long as you use it sparingly it shouldn't be that much of a problem. Furthermore is you basically use it as a replacement for reflection (that is you use dynamic only for the briefest possible durations when you want to access something via reflection), the risk of such bugs shouldn't be significantly higher then if you use reflection to access your methods/properties (of course if you make everything dynamic it can be more of a problem).

Affects interoperability with previous .NET versions

For that you have to decide yourself how much of a concern it is for you.

Pulchia answered 10/1, 2011 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.