Is Dynamic in C# Actually Slow?

preview_player
Показать описание


Hello everybody I'm Nick and in this video I will try to show you the real impact of using dynamic in C#, try to understand why it was added and compare it to alternatives to see how slow it really is.

Don't forget to comment, like and subscribe :)

Social Media:

#csharp #dotnet #dynamic
Рекомендации по теме
Комментарии
Автор

I'm now planning on using dynamic in automated UI tests. Some UI elements are defined based on runtime information. These will be accessible in tests as dynamic properties, like staticly defined elements (as opposed to GetDynamicElement("name") ) to beautify the testing interface. The performance shouldn't matter – UI testing steps take very long anyway.

zwatotem
Автор

I'd be interested to see how this works with operators performance-wise. A common use case I find that people leverage dynamic for is older versions of C# (i.e. pre-generic math) when they wish to, for example, add two enum members together using only generic type constraints (where T : struct, Enum). There's a multitude of ways one could use (assume integer and cast - doesn't work if the enum is 'ulong' for example; use cached reflection to retrieve the correct add method; emit and cache IL; and, for a lot of people the easiest, use dynamic).

Neonalig
Автор

I use dynamic only in the form of ViewBag that is in Web Applications. It mades communication between server and client easier. I mainly use it for giving a title to webpage dynamically.

stranger
Автор

Congratulations for the video Nick, great content as always. I have a question... does it make any sense to use dynamic DTOs for integration testing (and avoid using the production DTOs) ? I personally follow this approach so that in case a rename is done on a production DTO attribute, this would lead to a test failure. I guess another way to secure that is by replicating the DTO classes in the test projects, but I have adopted dynamic types as I believe they better simulate the way an API consumer would compose an HTTP request body.

Would like your opinion on this one 😄

stavrosk.
Автор

In 20 years of writing C# code I've never once used dynamic. If anything, this video showed me that the performance of dynamic is way better than I would have guessed. I don't see myself starting to use it though - it's just not the right solution to the kinds of problems I need to solve in C#. Unless I decide to host IronPython in an app, which it turns out, I just might for a current project - that's what dynamic was made for and is likely the only thing I would ever use it for.

carldaniel
Автор

I'm surprised you didn't mention the reading and writing of JSON and using dynamic. I like it as JSON and versioning isn't a real thing without schemas. I read what is provided, and use a string, dynamic dictionary to hold the key value pair.

snapching
Автор

I've used dynamic in a couple of scenarios moderately recently. The first (and main one) was when I was working with an Excel add-in that had to work on multiple versions of Excel, but with PIAs that effectively became incompatible across versions based on the COM object returned from Excel. Complex solution probably involved two DLLs in different domains (when was the last time you needed to use global:: before a namespace def?). That would have been horrible and it was a relative edge case so dynamic + try/catch/notify worked.

The second was in a set of helper methods for working with reflection. Using dynamic in an unusual scenario enabled me to avoid numerous headaches around mapping types correctly for the general case. Basically it was acting like Object but in a scenario where the called method took or returned a strict (but unknown and unspecifiable, typically because of accessibility specifiers) type. Passing around a dynamic meant that known methods could be called even if they had an internally typed parameter.

tobyjacobs
Автор

I've seen codebase where the guy who wrote it used ExpandoObject everywhere. It was nightmare, I can't unsee it.

AcidNeko
Автор

I use dynamic with numerics. Before INumeric, if you had two numeric types, you couldn't easily multiply or add without it. It's still not that easy because if you have two different numeric types like int vs double, multiplying them when their type is known is easy, but if their type is unknown, dynamic is the only way still (I'm aware of).

urbanelemental
Автор

"Always Be Measuring" makes a great catchphrase a'la "Always Be Closing".

Also, make sure sth like CreateDelegate is not applicable before using any of those.

klocugh
Автор

Interesting video. Currently I'm using dynamic to operate with SharePoint lists through Microsoft graph since people can just keep adding or removing columns to those and I always need to get all data available.

zagoskintoto
Автор

I only ever had to use Dynamic in one case in my previous job and that was to call a badly written php endpoint where in some cases it would return an array of something and in some cases it would return an object of something else. So instead of writing truly complicated code to read the result I just used the dynamic to parse it from json and then move by mapping it into an appropriate poco object. I was making an adapter between that endpoint and Dynamics CRM back then.

nickpolyderopoulos
Автор

I remember I used dynamic once as a method parameter to access a property on multiple types that had the same type and name, I assume I couldn't change the objects I was dealing with to implement an interface.

Vaelosh
Автор

I had a situation where I wanted to write a Visitor pattern implementation for a graph of entities which I could not control. So I couldn't add .Visit() methods to each entity, to call back in to the visitor.Accept() methods with complete type information. So what I ended up with was using dynamic: The first dynamic told the compiler to choose and bind the .Accept() method override at runtime, and the second dynamic told the compiler to use the runtime type of the entity object as the argument. It worked like a charm and the performance wasn't even too bad. Unfortunately sonarqube complained about all those .Accept() methods apparently being unreferenced (even though they were all covered by unit tests, so they were clearly getting called!). I'm not recommending this strategy to anybody else, just pointing out that dynamic has some uses when other methods of solving problems fail because of lack of compile-time type info.

wknight
Автор

The only time that I needed to use dynamic type in C# was interoperability calls to an application written in VB6. I use reflection when calling C# objects that I don't know the type of the caller.

MichaelBattaglia
Автор

Sometimes you don't have much choice and you're working with truly dynamic data that you have to represent somehow, either as a Dictionary or some other means e.g. a tagged data structure. I've just worked on a system that has an API taking in a tagged structure i.e. a type that has a Type member and a Data member. This API has no idea what it will be working with, it's function is to take this data and store the JSON string in the database and also retrieve it from the database and at some point the program will have the dynamic data serialized into a known type. I once wrote a small 2D game engine in C++ and it had a Lua scripting interface that exposed some of the C++ classes. The Lua primitives had to be converted into C++ primitives at runtime, the data was pushed onto a shared stack whereby Lua function calls push their args onto this stack when calling into the C++ functions and C++ pushes back any return values back to Lua. Sometimes data is in a raw format, it's just bytes and that's all you know about it at the time. Usually the data goes through some pipeline that converts the data into known types but there is an intermediary stage where you have truly dynamic runtime data and it has to be represented somehow be it a 'dynamic' object or a simple void* and size_t. If you interface with other language runtimes, you will inevitably have to convert the primitive or user types between these runtimes, but there's not many other legitimate reasons to be using dynamic. If you can possibly know the type at compile time (even if you have to use some nullable fields) it's far better than having runtime known only values.

fredhair
Автор

I use it mostly when endpoint http response with json does not have strict structure and may vary from request to request, for other situations I prefer to create definition for response explicitly.

SeymourRu
Автор

I had never used dynamic for anything until i tried using a charting package. my Mata was stored in a dictionary and the package required a pre defined class. Luckily there was a solution using an expandoobject. That seemed to be a better solution than copying fields around

SparkyHou
Автор

It was created in a time when C# was used to interface with COM and MS Office automation. A time, when "objects" were "remote" and changed their properties and classes villy nilly left and right at runtime.

der.Schtefan
Автор

I've found exactly only one application of dynamic in all my codebase, but it is really very efficient. I am using it in one very low level place where I invoke method over reflection and get result as Task, then I await that task and want to get result if it is generic task and null if not, I just do this ((dynamic) task).Result and it is magically returns result in minimal possible time. This time is comparable to cached reflection and even slightly better, but it needs no caching at all, and I don't want to apply caching in that place, cause it can outcome in caching almost every property and method of every type in whole application. I use reflection cache only in places where diversity of cached types is small and controlled, but in such abstract and hot path in app dynamic does it's best.

iGexogen