Assembly.Load() in multiple methods within the same class to load the same assembly - optimal or not?

StackOverflow https://stackoverflow.com/questions/14607278

Question

I have a class with several methods (e.g. Method1, Method2, Method3) and inside each method I load an assembly (same one in each method) and invoke a certain method (reflection) like this:

void Method1() // error handling etc. omitted
{
    Assembly asm = Assembly.LoadFrom(path);

    Type type = asm.GetType(classname);
    MethodInfo methodInfo = type.GetMethod("MethodName", ...);
    var o = Activator.CreateInstance(type); 
    var result = methodInfo.Invoke(o, parameters);
}

Is it OK performance-wise to do reflection this way, provided that all these methods load the same assembly? The code then looks like this:

obj.Method1(); // calls Assembly.Load()
obj.Method2(); // calls Assembly.Load()
obj.Method3(); // calls Assembly.Load()

or would it be better to load the assembly (and possibly GetType) only once in a separate method, store the reference to a class Assembly property and inside methods (Method1, Method2, Method3..) use this reference instead of always calling Assembly.Load()? This way, the code would look something like:

obj.LoadMyAssembly(); // calls Assembly.Load() and uses obj.MyAssembly property to store the reference
obj.Method1() // doesn't call Assembly.Load(), uses obj.MyAssembly instead
obj.Method2() // doesn't call Assembly.Load(), uses obj.MyAssembly instead
obj.Method3() // doesn't call Assembly.Load(), uses obj.MyAssembly instead

Does it make any difference? Domains etc. are never changed (or even used) inside the code.

Was it helpful?

Solution

There is no big difference as the assembly will be loaded in the same context. Then, if the assembly is already loaded, it won't reload it even if you call Assembly.LoadFrom(path);

However, if you already know that all the method are in the same assembly, it could be better to call Assembly.LoadFrom only once.

OTHER TIPS

As far as I know, load the same assembly more than once would not cause performance issues. However, look into your method, there is

var o = Activator.CreateInstance(type); 

You are invoking a member method, on a definitely a new instance of object of the type.

Though it might not cause problems, but just a redundant behavior, isn't it? I think that just wasting, and increase garbages to collect on your heap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top