Does reflection in .Net use the performance effect badly?

Possible duplicate:
How much does Reflection cost?

To create my generic code, I started using Reflection - to get some properties in DTO objects and to set them -

Is the use of reflection used to get properties and set them, since performance can be much worse than hard-coded setters?

+4
source share
3 answers

Yes , there are costs associated with using Reflection.

However, the actual impact on overall application performance is changing. One rule: never use Reflection in code that runs many times , such as in a loop. This usually slows down the exponential algorithms (O (c n )).

In many cases, you can write common code using delegates instead of Reflection, as described in this blog post .

+4
source

Yes, the reflection is slow. You can try to reduce the impact of this by caching xxxInfo objects (for example, MethodInfo objects, PropertyInfo objects, etc.) that you retrieve using reflection on the reflected type, and, i.e. Keep them in the dictionary. Subsequent searches in the dictionary are faster than retrieving information each time.

You can also search here in SO for some questions about reflection performance. For some edge cases, there are fairly effective workarounds, such as using CreateDelegate to call methods instead of using MethodInfo.Invoke() .

+1
source

Besides being slower in setting properties through reflection, this is a design issue, since you apparently shared problems or encapsulated properties through an object-oriented design, which now prevents you from setting them directly. I would say that you look at your design (for example, there may be edge cases) instead of thinking about reflection.

One of the drawbacks, in addition to the impact of performance, is that you use a statically typed language, which is why the compiler checks your code and compiles it. Usually at compile time you are sure that all the properties that you use are and are written correctly. When you start using reflection, you push this check at runtime, which is a real shame, since you (in my opinion) lack one of the biggest advantages of using a static typed language. It will also limit the possibility of refactoring in the near future, since you are not sure if you replaced all cases of assignment, for example, when renaming a property.

0
source

Source: https://habr.com/ru/post/1369118/


All Articles