Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the performance of reflection APIs such as GetType() and GetTypes()? [duplicate]

I use reflection APIs such as GetType() and GetTypes() in .NET/C#.

  • In terms of performance, how good or bad are those APIs? I mean, are these APIs take much time that might cause some performance degradation, or are these APIs well designed to ignore performance issues?
  • Do normally people caching the results when they use the reflection APIs?
like image 809
prosseek Avatar asked Jun 20 '11 13:06

prosseek


1 Answers

We don't know what "good" and "bad" mean to you.

We don't know if you are using these in critical performance code that is likely to be a bottleneck to your application.

Only you know exactly the paths your code will take when using Object.GetType and Assembly.GetTypes.

Therefore, only you can profile exactly how meaningful the use of these methods will be on the performance of your application, and how beneficial it will be to try to boost the performance through caching.

I can tell you this: I have never had Type.GetType and Assembly.GetTypes be a bottleneck in my application, and I don't cache the results (I have, however, needed to cache MemberInfo.GetCustomAttributes but I only came to that conclusion after a profiler told me that it was a significant bottleneck in my application and that caching would substantially improve the performance).

Responding to your edit:

I mean, are these APIs take much time that might cause some performance degradation, or are these APIs well designed to ignore performance issues?

What alternatives do you have? If you need a reference to Type for a given object, or you need all the types in a given assembly, I assure you that Object.GetType and Assembly.GetTypes are your best choice. The question is, how are you using them? Again, we don't know, and therefore can't tell you what to do. You have to profile your real-world use of these functions and find out if they are causing a bottleneck in your application or not.

like image 133
jason Avatar answered Sep 21 '22 12:09

jason