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

前端 未结 6 867
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 02:22

Suppose you have a class Person :

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


        
6条回答
  •  一个人的身影
    2020-12-23 03:25

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

    It returns EmptyEnumerable.Instance, which is defined as:

    internal class EmptyEnumerable
    {
        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(), Enumerable.Empty()));
    

提交回复
热议问题