I'm using RedGate to do some performance evaluation. I notice dynamically creating an instance using Activator.CreateInstance
(with two constructor parameters) is taking a decent amount of time... is there a better alternative that still utilizes a reflective approach (not explicit instantiation)?
The Activator. CreateInstance method creates an instance of a type defined in an assembly by invoking the constructor that best matches the specified arguments. If no arguments are specified then the constructor that takes no parameters, that is, the default constructor, is invoked.
CreateInstance(ActivationContext) Creates an instance of the type designated by the specified ActivationContext object. CreateInstance(AppDomain, String, String) Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and parameterless constructor.
Reflection is not THAT slow. Invoking a method by reflection is about 3 times slower than the normal way. That is no problem if you do this just once or in non-critical situations. If you use it 10'000 times in a time-critical method, I would consider to change the implementation.
Use a compiled lambda if you can, its MUCH faster.
https://vagifabilov.wordpress.com/2010/04/02/dont-use-activator-createinstance-or-constructorinfo-invoke-use-compiled-lambda-expressions/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With