c# - 使用 Enumerable.Empty<T>() 而不是 new List<T>() 来初始化 IEnumerable<T> 是否更好?

标签 c# linq constructor

假设你有一个类 Person :

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

我显然应该在构造函数中实例化角色。 现在,我曾经用这样的列表来做:

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

但是我在System.Linq命名空间中发现了这个静态方法

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

来自 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

那么这样写构造函数是不是更好呢?你用吗?为什么?如果不是,为什么不呢?

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

最佳答案

我认为大多数帖子都没有捕获要点。即使您使用空数组或空列表,它们也是对象并且存储在内存中。垃圾收集器必须照顾他们。如果您正在处理高吞吐量应用程序,它可能会产生明显的影响。

Enumerable.Empty 不会在每次调用时创建对象,从而减轻 GC 的负载。

如果代码位于低吞吐量位置,则归结为美学考虑。

关于c# - 使用 Enumerable.Empty<T>() 而不是 new List<T>() 来初始化 IEnumerable<T> 是否更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1894038/

相关文章:

c# - 动态 LINQ GroupBy 多列

Angular - 如果它没有任何逻辑,我们还需要一个构造函数吗

java - 使用 self(this) 参数在构造函数中调用构造函数

c# - Microsoft Rest ServiceClientTracing - 如何将跟踪结果输出到控制台或调试?

c# - 带有构造函数的通用类<T>来选择类型

c# - 如何在启动时将表单加载更改为其他表单?

c# - NHibernate 不支持指定的方法

C# 在 lambda 表达式中声明变量

c# - 使用 .NET 程序集的 Delphi 出现 OLE 错误 8013150A(以管理员身份运行奇怪)

c++ - 范围解析运算符被使用两次