How is the performance of the display API like GetType () and GetTypes ()?

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

  • In terms of performance, how good or bad are these APIs? I mean that these APIs are time consuming, which can lead to some performance degradation, or are these APIs well designed to ignore performance issues?
  • Do people usually cache results when they use the reflection API?
+6
source share
2 answers

We do not know what “good” and “bad” mean to you.

We do not know if you use them in critical performance code, which is likely to become a bottleneck for your application.

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

Therefore, only you can determine exactly how significant the use of these methods will be in the performance of your application, and how useful it will be to try to improve performance using caching.

I can tell you the following: I never had Type.GetType and Assembly.GetTypes be a bottleneck in my application and I did not cache the results (I, however, need to cache MemberInfo.GetCustomAttributes , but I only came to this conclusion after that as the profiler told me that this is a serious bottleneck in my application and that caching will significantly improve performance).

Reply to your edit:

I mean, do these APIs take a lot of time, which can lead to some performance degradation, or are these APIs well designed to ignore performance issues?

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

+6
source

Both of them are extremely effective and work very poorly. It all depends on your perspective and comparison.

Reflection APIs reflect the goal, and in most cases using these APIs they will not create a bottleneck. Use them.

If, after intensive use, they do create a bottleneck that is displayed using profiling, there are options for improving productivity. You can implement caching on your part, and you can use runtime or compilation generation.

Most ORMs use reflection to populate entity objects, and since this is something that is done multiple times in a very large amount, it can become a performance bottleneck. Some new microlevels use classes created at runtime that can create objects without reflection (using Reflection.Emit). In our project, we use classes created using compilation to create collectors for each object. The generated compilation time is simpler and has better performance if it works in your situation.

+4
source

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


All Articles