Here's a simple question : Is there any (performance) difference between this :
Person person = new Person()
{
Name = "Philippe",
Mail = "[email protected]",
};
and this
Person person = new Person();
person.Name = "Philippe";
person.Mail = "[email protected]";
You can imagine bigger object with more properties.
They are almost exactly equivalent except that the first method (using an object initializer) only works in C# 3.0 and newer. Any performance difference is only minor and not worth worrying about.
They produce almost identical IL code. The first gives this:
The second gives this:
As you can see, nearly identical code is generated. See below for the exact C# code I compiled.
Performance measurements show very similar results with a very small performance improvement for using the object initializer syntax:
Code I used for testing the performance: