使用Enumerable.Empty< T>()而不是新的List< T>()来初始化IEnumerable< T> [英] Is it better to use Enumerable.Empty<T>() as opposed to new List<T>() to initialize an IEnumerable<T>?
问题描述
假设你有一个Person类:
public class Person
{
public string Name {得到; set;}
public IEnumerable< Role>角色{get; set;}
}
我应该在构造函数中实例化角色。
现在,我以前用这样的列表:
public Person()
{
Roles = new List< Role>();
}
但我在系统中发现了这个静态方法。 Linq
命名空间
IEnumerable< T> Enumerable.Empty< T>();
从 MSDN :
c $ c> Empty(TResult)()方法缓存
类型为TResult
的空序列。当
时,它返回的对象被枚举,
它不会产生任何元素。
在某些情况下,这种方法是有用的
的示例
一个空序列到
用户定义的方法,它接受
IEnumerable(T)
。它也可以用于
为方法
生成中性元素,例如Union
。请参阅示例部分
以获取使用
那么最好写这样的构造函数吗?你使用它吗?为什么?或如果不是,为什么不呢?
public Person()
{
Roles = Enumerable.Empty&
}
要点。即使使用空数组或空列表,这些都是对象,它们存储在内存中。比垃圾收集者必须照顾他们。如果您正在处理高吞吐量应用程序,它可能会产生明显的影响。
Enumerable.Empty
每个呼叫对象,因此对GC的负载较小。
如果代码在低吞吐量位置,那么它可以归结为审美的考虑。 $ b
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 typeTResult
. 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 asUnion
. 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>();
}
I think most postings missed the main point. Even if you use empty array or empty list, those are objects and they are stored in memory. Than Garbage Collector has to take care of them. If you are dealing with high throughput application, it could be noticeable impact.
Enumerable.Empty
does not create an object per call thus putting less load on GC.
If the code is in low-throughput location, then it boils down to aesthetic considerations though.
这篇关于使用Enumerable.Empty< T>()而不是新的List< T>()来初始化IEnumerable< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!