Search code examples
c#design-patternsobjectinstantiationobjectinstantiation

Is Object Literal Instantiation faster than setting properties?


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

Solution

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