This repo demonstrates various ways to create an instance of a type at runtime, and includes a Benchmark.NET project to measure and compare their performance. All code is MIT-licensed.
Two scenarios are considered:
-
You need to create an instance of a type, and you have the appropriately-typed arguments for that type's constructor at design-time. This scenario allows the code to use a generic method to get the argument types, in order to find a matching constructor.
-
You need to create an instance of a type, and you have the constructor arguments all typed as
object
. This scenario requires the code to callGetType()
on each argument, in order to find a matching constructor.
For each scenario, parameterless, 1-, 2- and 3-parameter constructor objects are created. In the 3-parameter case the type has multiple constructors, and the code has to pick the correct one.
The following methods are measured and compared:
-
Using
new
. This is used as the design-time baseline. -
Using a design-time method I wrote about in 2012.
-
Using an updated design-time method I wrote in 2020.
-
Using
Activator.CreateInstance
, a runtime method in the Base Class Libraries. -
Using a runtime method I wrote in 2020.
Example benchmarking results for .NET Core 3.1 are shown below:
To note:
-
My 2020 design-time code is between 1.5 and 2.5 times faster than my 2012 code.
-
My 2020 runtime code is between 6.7 and 6.9 times faster than
Activator.CreateInstance
for all except the parameterless case. It's 1.3 times slower for parameterless constructors.
Further discussion can be found on my blog.