Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Type.GetType() slow down based on the size and complexity of the object you are retrieving?

Tags:

c#

reflection

I have an application that is using basic reflection today to grab classes.

Type type = Type.GetType(mynamespace.myclassname);
object o = System.Activator.CreateInstance(type);

I wanted to see how efficient the reflection was running so I generated about 150,000 objects in this manner to see if performance ever degraded and performance was fast and steady.

However, this got me thinking: Will the call to Type.GetType() actually slow down depending on the size and complexity of the class being passed into the GetType() method?

For example: Lets say we wanted to use GetType() to retrieve a complex class made up of 30 private variables, 30 private methods and 30 public methods versus a class that has only one very simple public Add(int, int) method which sums up two numbers.

Would Type.GetType slow down significantly if the class being passed in is a complex class versus a simple class?

thanks

like image 948
Matt Avatar asked Feb 02 '23 09:02

Matt


2 Answers

According to my understanding of things, (and I am just a humble experienced programmer, I am not one of the creators of the language,) the complexity of the class which is being referred does not in any way whatsoever affect the performance of GetType().

The complexity of the instantiated class will of course affect the performance of CreateInstance(), but that is to be expected: the larger the class is, the more stuff it contains, the more code will need to be executed in order to fully construct it.

Perhaps you are confusing GetType() with CreateInstance(), because I notice you say "Would Type.GetType slow down significantly when instantiating the complex class versus the simple class?" while in fact GetType() does not instantiate anything, CreateInstance() does.

like image 179
Mike Nakis Avatar answered Feb 06 '23 10:02

Mike Nakis


An instance of the Type object fitting to your type is created when the type is loaded. This (one-time) process will obviously be more or less expensive depending on the type implementation.

After this, a call to GetType() will give you a reference to this readily-prepared instance, and will thus not degarde over time or complexity.

like image 30
Eugen Rieck Avatar answered Feb 06 '23 11:02

Eugen Rieck