Alex Rivera | Logout

Is Object Literal Instantiation faster than setting properties?

Asked 2012-08-15T19:30:44.357
9

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 };
}
Edit
Report

1 Answer

16

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.

answered 2012-08-15T19:31:45.540

Your Answer