Is it better to use Enumerable.Empty<T>() as opposed to new List<T>() to initialize an IEnumerable<T>?

Suppose you have a class Person :

public class Person
{
   public string Name { get; set;}
   public IEnumerable<Role> Roles {get; set;}
}

I should obviously instantiate the Roles in the constructor. Now, I used to do it with a List like this :

public Person()
{
   Roles = new List<Role>();
}

But I discovered this static method in the System.Linq namespace

IEnumerable<T> Enumerable.Empty<T>();

From MSDN:

The Empty(TResult)() method caches an empty sequence of type TResult. When the object it returns is enumerated, it yields no elements.

In some cases, this method is useful for passing an empty sequence to a user-defined method that takes an IEnumerable(T). It can also be used to generate a neutral element for methods such as Union. See the Example section for an example of this use of

So is it better to write the constructor like that? Do you use it? Why? or if not, Why not?

public Person()
{
   Roles = Enumerable.Empty<Role>();
}

Solution 1:

I think most postings missed the main point. Even if you use an empty array or empty list, those are objects and they are stored in memory. The Garbage Collector has to take care of them. If you are dealing with a high throughput application, it could be a noticeable impact.

Enumerable.Empty does not create an object per call thus putting less load on the GC.

If the code is in low-throughput location, then it boils down to aesthetic considerations though.

Solution 2:

I think Enumerable.Empty<T> is better because it is more explicit: your code clearly indicates your intentions. It might also be a bit more efficient, but that's only a secondary advantage.

Solution 3:

On the performance front, let's see how Enumerable.Empty<T> is implemented.

It returns EmptyEnumerable<T>.Instance, which is defined as:

internal class EmptyEnumerable<T>
{
    public static readonly T[] Instance = new T[0];
}

Static fields on generic types are allocated per generic type parameter. This means that the runtime can lazily create these empty arrays only for the types user code needs, and reuse the instances as many times as needed without adding any pressure on the garbage collector.

To wit:

Debug.Assert(ReferenceEquals(Enumerable.Empty<int>(), Enumerable.Empty<int>()));