Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activator.CreateInstance Performance Alternative

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)?

like image 782
Brian Mains Avatar asked Dec 13 '10 18:12

Brian Mains


People also ask

What does activator CreateInstance do?

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.

What is activator CreateInstance in net core?

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.

Is C# reflection slow?

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.


1 Answers

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/

like image 194
poindexter12 Avatar answered Oct 06 '22 20:10

poindexter12