Here are a few examples of how we can create objects, and the perf implications of each way. In all those tests, I have used the following class as my benchmark.
We have a value type and a reference type that are passed to the constructor.
The test code is here:
Here it my base line, calling the constructor directly.
This executes in 00.3648117 seconds on severely underpower laptop. Pretty good, considering we just created a million instances. Now, let us see what happens if we user Activator, shall we?
This run depressingly slow, 06.8242636 seconds.
Let us try to improve that a bit, using GetUninitializedObject and directly invoking the constructor.
This runs in 03.2422335 seconds, a significant improvement, but we can do even more, I think.
We start by making the required definitions:
Then we generate a dynamic method to create the object, and turn that into a delegate:
Now, in the method itself, all we have to do is call this delegate:
And now that run very fast... 00.4314517 seconds. Almost as fast as our baseline. But this is not really a good example, I am afraid. At least, not a god example of generally creating instances, let us make this into the more general form, shall we?
We will change the CreateCtor delegate to the following signature:
And the generation of the dynamic method to use the generic approach:
We need to make the following modification to our CreateInstance method:
And now it runs in.... 00.5018288.
Now, what does this long and arcane post tells us?
Creating instances, no matter how many, is really cheap. Remember that I had to do a million iteration to get something measurable.
The table bellow give the final statistics. Pay attention to the last column, this gives the amount of time it take to create a single instance. Even the most hard core perf fanatic would be hard pressed to argue over 0.000007 seconds. At least I hope so :-)
|Create single instance||Iterations||Time||Method|
And just to clarify, you are not going to see anything like creating a million object in most scenarios that you care about. In other words, you can probably leave things well enough alone.