Here’s a link to the previous question I had, which led me to this one.
C# Nested foreach loop optimization
There is still high computation time, and I’m not sure what the cause is.
object foo;
List<string> StringList = new List<string>(); // Populated by previous code
Dictionary<string, Type> assemblyTypes = RandomAssembly.GetTypes().ToDictionary(t => t.Name, t => t);
foreach (String name in StringList)
{
if (assemblyTypes.ContainsKey(name))
{
// Create an instance of the matching class and add it
// to the appropriate lists.
Type at = assemblyTypes[name];
foo = Activator.CreateInstance(at);
ArbitraryList1.Add(foo);
}
}
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 callCreateInstanceyou want to keep a dictionary of their constructorsDictionary<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.
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