If the computation time is noticeably slow, I assume that you often call this code, and you create many objects that you know little about at compile time.
Instead of holding classes in a Dictionary<string, type> and calling CreateInstance , you want to save the dictionary of your Dictionary<string, ConstructorInfo> constructors so that you can call them directly without thinking about each reflection.
That way you can just call AssemblyConstructors [Name] .Invoke () to create a new instance of the class.
This way you only need to use reflection once to find the constructors.
I think the first constructor will be without parameters. Try something like t.GetConstructors().Where(x => x.GetParameters().Count() == 0).First(); This is the fastest way I know, because apparently you cannot get a delegate for the constructor .
If you write classes that you create yourself, you can have a common base class or interface with a method that creates it, so you can save a delegate to this constructor, which is even faster.
This post also has some interesting ideas about this that will optimize a lot more . If you want to do it fast, you can. Almost as fast as just calling new KnownClass()
Good luck
GJ
source share