I have investigated several methods for object creation in .NET, and although most demonstrate similar performance, there are some nuances. The examples below illustrate each approach.
Using the “new” Keyword
I would argue that the majority of code I come across follows the conventional method for creating objects:
var result = new Person();
or
Person result = new()
Activator.CreateInstance()
If an object needs to be created dynamically, an alternative method for object creation involves utilizing Activator.CreateInstance
, as demonstrated below. This approach generates an instance of the specified type by employing the constructor that most appropriately aligns with the provided parameters.
var instance = Activator.CreateInstance<Person>();
or
var instance = Activator.CreateInstance(typeof(Person));
RuntimeHelpers.GetUninitializedObject
In scenarios where an uninitialized object is necessary, one can utilize it as demonstrated below.
var person = RuntimeHelpers.GetUninitializedObject(typeof(Person));
Benchmark Results
The findings associated with the development of a reference type, as demonstrated in the previously mentioned examples, suggest that creating objects with new()
is more efficient. Specifically, it is 1.04 times faster than using the normal method to create objects, 1.72 times faster than using CreateInstance()
with typeof()
, 1.96 times faster than using Activator.CreateInstance()
, 2.1 times faster than using CreateInstance<>
and is 2.28 times faster than using GetUninitialiedObject()
.
My recommendation is to stick with using the normal way of creating objects or use
new()
, unless there is a specific reason to use a different method.
Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
DonateDonate monthlyDonate yearlyIf you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave
© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.