Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using reflection in .Net effects the performance reasonably bad? [duplicate]

Possible Duplicate:
How costly is Reflection?

For sake of making my code generic I have started to use Reflection -to obtain some proerties in DTO objects and to set them-

Does usage of reflection to obtain properties and set them can effect the performance so badly compared to hard-coded setters?

like image 432
pencilCake Avatar asked Aug 26 '11 07:08

pencilCake


2 Answers

Yes, there is a cost involved in using Reflection.

However, the actual impact on the overall application performance varies. One rule of thumb is to never use Reflection in code that gets executed many times, such as loops. That will usually lead to algorithms that slow down exponentially (O(cn)).

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

like image 60
Enrico Campidoglio Avatar answered Nov 18 '22 20:11

Enrico Campidoglio


Yes, reflection is slow. You can try to decrease the impact of it by caching the xxxInfo (like MethodInfo, PropertyInfo etc) objects you retrieve via reflection per reflected Type and, i.e. keep them im a dictionary. Subsequent lookups in the dictionary are faster than retrieving the information every time.

You can also search here at SO for some questions about Reflection performance. For certain edge-cases there are pretty performant workarounds like using CreateDelegate to call methods instead of using MethodInfo.Invoke().

like image 2
Sebastian P.R. Gingter Avatar answered Nov 18 '22 18:11

Sebastian P.R. Gingter