Question

  1. Are there any speed gains when initializing a large amount of static objects?
  2. Are there any compile-time or other kinds of advantages?

e.g:

IList<object> objects = new List<object>
{
    new object(),
    new object(),
    new object()
};

vs:

IList<object> objects = new List<object>();
objects.Add(new object());
objects.Add(new object());
objects.Add(new object());
Was it helpful?

Solution

There is no run time difference between these two pieces of code. They will both compile down to the same IL.

The primary advantage of the initializer syntax would be that it basically initializes a list in a single expression as opposed to across multiple statements. For example, you could use it to return a list from a method without explicitly creating a temporary variable (the compiler creates this temporary for you):

public List<T> MakeListOf3<T>( T val )
{
    return new List<T> { val, val, val };
}

As opposed to:

public List<T> MakeListOf3<T>( T val )
{
    var list = new List<T>();
    list.Add( val );
    list.Add( val );
    list.Add( val );
    return list;
}

That's quite contrived, but you get the idea.

OTHER TIPS

It's basically a syntactical sugar and it's rather a matter of personal taste and aesthetics.

Also, it's worth mentioning that it's possible to combine collection initializers and object initializers. You can than build in one run pretty complex structures, e.g.:

Product product = new Product
{
    Name = "Dog food",
    Price = 9.95,
    Manufacturer =
    {
        Name = "Dog food producer"
        Location = "Some location"
    },
    SimilarProducts =
    {
        new Product { Name = "Cat food" },
        new Product { Name = "Bird food", Price = 5.50},
        new Product 
        { 
            Name = "Guinea Pig food", 
            Price = 5.50
            SimilarProducts = 
            { 
                new Product { Name = "Guinea Pig shampoo" }, 
                new Product { Name = "Guinea Pig toofpaste" }
            },
        },
    },
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top