High computation time

Here was a link to a previous question that led me to this. C # Nested foreach loop optimization

There is still a lot of computation time, and I'm not sure what the reason 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); } } 
+2
source share
3 answers

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.

 // 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 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

+3
source

Summary: A substantially unlimited loop with one of the slowest functions in a structure called each iteration will be slow.

There are many approaches to avoid reflection, but without any other information that you just need to live with.

+1
source

Use Dictionary.TryGetValue to search for the name key once instead of two. This is just a small tip, as I'm sure reflection is a bottleneck.

0
source

All Articles