2

I have an application that loads Type by reflection upon need since implementation may be changed by configuration. here is a sample code:

var myObject = Activator.CreateInstance(Type.GetType("MyAssembly.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1r46a5dfa04dase2"))as IMyClass

My Question here, is this Type being cached by default or it will be reloaded every time, and if not, How can I cache it to enhance performance?

Basyonic
  • 447
  • 4
  • 9

2 Answers2

0

Unlike instances, single types and their containing assemblys are,once used, not unloaded (assuming only one AppDomain), so basically the answer is yes, there is a cache.

Also have a look here: Can you remove an Add-ed Type in PowerShell again?

Community
  • 1
  • 1
Udontknow
  • 1,472
  • 12
  • 32
0

Once loaded an assembly can't be unloaded (unless you unload the full AppDomain that loaded it) (see for example How to unload an assembly from the primary AppDomain?). So there is the opposite problem of yours :-)

Now... You can surely speed up everything:

Type myType = Type.GetType("MyAssembly.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1r46a5dfa04dase2");

This call will need to be executed every time. While the assembly won't be loaded, a search in the assembly will be done. You can cache myType.

var myObject = Activator.CreateInstance(myType) as IMyClass;

This will search for a parameterless constructor for myType every time. You could speed up this by caching the constructor (myConstructor) you need:

ConstructorInfo myConstructor = myType.GetConstructor(Type.EmptyTypes);

var myObject = myConstructor.Invoke(null) as IMyClass;

Now... Even using reflection is slow... you could create a dynamic method that invokes the constructor and cache it:

Func<IMyClass> myCreate = Expression.Lambda<Func<IMyClass>>(Expression.New(myConstructor)).Compile();

var myObject = myCreate();

So in the end you could cache only myCreate :-)

Community
  • 1
  • 1
xanatos
  • 109,618
  • 12
  • 197
  • 280