Is Object Literal Instantiation faster than setting properties?

3.1k Views Asked by At

Given the following example, is one objectively better/faster/safer than the other? Should object literal instantiation be a best practice where it is practical?

Where is this inappropriate?

class Person
{
    public string name;
    public int age;
}
void MakePeople()
{
    Person myPerson = new Person();
    myPerson.name = "Steve";
    myPerson.age = 21;

    Person literalPerson = new Person { name = "John", age = 22 };
}
4

There are 4 best solutions below

7
On BEST ANSWER

No, it isn't faster or slower. It is the same.

The compiler translates object initializers to a constructor call followed by setting those properties.

Person literalPerson = new Person { name = "John", age = 22 };

Turns to:

Person myPerson = new Person();
myPerson.name = "John";
myPerson.age = 22;

You should use what is more readable and what you have agreed on with your team.

0
On

I don't think speed should be what drives this decision. There is probably very little difference between the speed of either method.

I think code readability should be the prime factor in which way you go. Using that criteria, I think they are very close and it comes down to personal preference or whatever your team decides on. However, I think in the case of a object with requires many properties to be set, explicitly calling setters is a little more readable.

0
On

If you take a look at the IL that is generated, I'm pretty sure you'll find that they are identical. Using object initializers is just a compiler shortcut.

5
On

Either is appropriate. It depends on what you need to do to set properties. For example, I would avoid literal instantiation in cases where some logic is needed to arrive at a property value:

Person myPerson = new Person();
myPerson.SomeProperty = if IsNewPerson ? GetPropertyFromDatabase() : GetDefaultProperty();

Edit:

One advantage to using literal object initialization in Visual Studio is that Intellisense will prompt for properties, showing only those which have not already been declared. (I've ran into code where a value was redundantly assigned when setting properties.)