Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance improvement if using an object initializer, or is it asthetic?

Tags:

c#

So, the comparison would be between:

MyClass foo = new MyClass();
foo.Property1 = 4;
foo.Property2 = "garfield";

and

MyClass foo = new MyClass { Property1 = 4, Property2 = "garfield" };

Is it syntactic sugar, or is there actually some kind of performance gain (however minute it's likely to be?)

like image 547
Paul Avatar asked Jul 31 '09 22:07

Paul


4 Answers

I'ts syntactic sugar and the compiler generates the same exact IL as it did before object initializers were introduced in .NET 3.5

like image 187
Abhijeet Patel Avatar answered Oct 11 '22 19:10

Abhijeet Patel


It's actually potentially very, very slightly slower to use an object initializer than to call a constructor and then assign the properties, as it has one extra assignment:

MyClass foo = new MyClass();
foo.Property1 = 4;
foo.Property2 = "garfield";

vs

MyClass tmp = new MyClass();
tmp.Property1 = 4;
tmp.Property2 = "garfield";
MyClass foo = tmp;

The properties are all assigned before the reference is assigned to the variable. This difference is a visible one if it's reusing a variable:

using System;

public class Test
{
    static Test shared;

    string First { get; set; }

    string Second
    {
        set
        {
            Console.WriteLine("Setting second. shared.First={0}",
                              shared == null ? "n/a" : shared.First);
        }
    }

    static void Main()
    {
        shared = new Test { First = "First 1", Second = "Second 1" };
        shared = new Test { First = "First 2", Second = "Second 2" };        
    }
}

The output shows that in the second line of Main, when Second is being set (after First), the value of shared.First is still "First 1" - i.e. shared hasn't been assigned the new value yet.

As Marc says though, you'll almost certainly never actually spot a difference.

Anonymous types are guaranteed to use a constructor - the form is given in section 7.5.10.6 of the C# 3 language specification.

like image 40
Jon Skeet Avatar answered Oct 11 '22 18:10

Jon Skeet


It is entirely sugar for standard types. For anonymous types, you may find that it uses a constructor behind the scenes, but since the initializer syntax is the only way of assigning them, it is a moot point.

This involves a few more calls than, say, a specific constructor - but I'd be amazed if you ever saw a difference as a result. Just use initializer syntax - it is friendlier ;-o

like image 20
Marc Gravell Avatar answered Oct 11 '22 18:10

Marc Gravell


No there is no performance improvement. Under the hood the compiler will generated assignments to the same properties and fields. It will look just like your expanded version.

like image 21
JaredPar Avatar answered Oct 11 '22 19:10

JaredPar