If the computation time is noticeably slow I guess you're calling into this code a lot and you're newing up a lot of objects that you don't know much about at compile time.
Instead of keeping the classes in a Dictionary<string, type>
and call CreateInstance
you want to keep a dictionary of their constructors Dictionary<string, ConstructorInfo>
so you can call them directly without having to look for it every time with reflection.
That way you can just call AssemblyConstructors[Name].Invoke() to create a new instance of the class.
This way you only have to use reflection once to find the constructors.
// keep a dictionary of constructors (instead of the types)
var Constructors = new Dictionary<string, ConstructorInfo>();
// add this class to this dictionary
Type t = typeof(SomeClass);
string name = t.Name;
Constructors[name] = t.GetConstructors()[0]; // use reflection only once here, afterwards we reuse the reflected info
// new up an instance
var o = Constructors[name].Invoke(new object[] {});
I think the first constructor will be the parameterless one. Else try something like t.GetConstructors().Where(x => x.GetParameters().Count() == 0).First();
This is the fastest easy way I know because apparently you can't get a delegate to a constructor.
If you write the classes you're newing up yourself, you can have a common base class or interface with a method that creates one, that way you can keep a delegate to that constructor, that's even faster.
This post also has some interesting ideas about this that take optimization much further. If you want to do this fast, you can. Almost as fast as just calling new KnownClass()
Good luck,
GJ