Does System.Activator.CreateInstance(T) method have performance issues (since I’m suspecting it uses reflection) big enough to discourage us from using it casually?
Does System.Activator.CreateInstance(T) method have performance issues (since I’m suspecting it uses reflection) big enough
Share
As always, the only correct way to answer a question about performance is to actually measure the code.
Here’s a sample LINQPad program that tests:
As always, take the performance program with a grain of salt, there might be bugs here that skews the results.
The output (timing values are in milliseconds):
Note that the above timings are for 100.000.000 (100 million) constructions of the object. The overhead might not be a real problem for your program.
Cautionary conclusion would be that
Activator.CreateInstance<T>is taking roughly 11 times as much time to do the same job as anew T()does, and a delegate takes roughly 1.5 times as much. Note that the constructor here does nothing, so I only tried to measure the overhead of the different methods.Edit: I added a baseline call that does not construct the object, but does the rest of the things, and timed that as well. With that as a baseline, it looks like a delegate takes 75% more time than a simple new(), and the Activator.CreateInstance takes around 1100% more.
However, this is micro-optimization. If you really need to do this, and eek out the last ounce of performance of some time-critical code, I would either hand-code a delegate to use instead, or if that is not possible, ie. you need to provide the type at runtime, I would use Reflection.Emit to produce that delegate dynamically.
In any case, and here is my real answer:
And just to make sure I actually answer your concrete question: No, I would not discourage use of Activator.CreateInstance. You should be aware that it uses reflection so that you know that if this tops your profiling lists of bottlenecks, then you might be able to do something about it, but the fact that it uses reflection does not mean it is the bottleneck.
The program: