An example repo demonstrating and measuring various ways of creating an instance from a type at runtime.
Перейти к файлу
randomC0der d55b9e8ff8
Skip loop for zero arguments (#2)
2021-04-09 07:23:06 +01:00
CreateInstanceFromType Skip loop for zero arguments (#2) 2021-04-09 07:23:06 +01:00
CreateInstanceFromType.Benchmark Differentiating between design-time and runtime args methods 2020-07-11 08:26:56 +01:00
CreateInstanceFromType.Tests Valuetype bugfix (#1) 2021-04-08 18:08:47 +01:00
.gitignore Initial commit 2020-07-09 19:24:37 +01:00
CreateInstanceFromType.sln Adding readme 2020-07-11 09:25:28 +01:00
LICENSE Initial commit 2020-07-09 19:24:37 +01:00
README.md Updated results 2020-07-11 12:35:25 +01:00
Results.png Updated results 2020-07-11 12:35:25 +01:00

README.md

Creating an Instance of a Type at Runtime

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.

Scenarios

Two scenarios are considered:

  1. 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.

  2. 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 call GetType() 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.

Methods

The following methods are measured and compared:

  1. Using new. This is used as the design-time baseline.

  2. Using a design-time method I wrote about in 2012.

  3. Using an updated design-time method I wrote in 2020.

  4. Using Activator.CreateInstance, a runtime method in the Base Class Libraries.

  5. Using a runtime method I wrote in 2020.

Results

Example benchmarking results for .NET Core 3.1 are shown below:

Benchmarking Results

To note:

  1. My 2020 design-time code is between 1.5 and 2.5 times faster than my 2012 code.

  2. 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.