Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Object Literal Instantiation faster than setting properties? [duplicate]

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 };
}
like image 357
Wesley Avatar asked Aug 15 '12 19:08

Wesley


2 Answers

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.

like image 69
Oded Avatar answered Nov 20 '22 19:11

Oded


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

like image 33
JYelton Avatar answered Nov 20 '22 18:11

JYelton