是产量突破相当于返回可枚举< T> .Empty从返回的IEnumerable℃的方法; T> [英] Is yield break equivalent to returning Enumerable<T>.Empty from a method returning IEnumerable<T>
问题描述
这两种方法出现同样的行为给我
These two methods appear to behave the same to me
public IEnumerable<string> GetNothing()
{
return Enumerable.Empty<string>();
}
public IEnumerable<string> GetLessThanNothing()
{
yield break;
}
我在测试场景异形每我没有看到一个有意义的在速度上的差异,但产量突破
版本稍微快一些。
有没有使用一个比任何原因其他?是其中一个比另一个更容易阅读?有没有一种行为的差异,将关系到呼叫者?
Are there any reasons to use one over the other? Is one easier to read than the other? Is there a behavior difference that would matter to a caller?
推荐答案
如果您打算始终返回一个空枚举然后使用 Enumerable.Empty<串GT;()
语法更具声明恕我直言。
If you intend to always return an empty enumerable then using the Enumerable.Empty<string>()
syntax is more declarative IMHO.
下面的性能差异几乎可以肯定不会显著。我将侧重于可读性在这里的表现,直到探查表明你这是一个问题。
The performance difference here is almost certainly not significant. I would focus on readability over performance here until a profiler showed you it was a problem.
这篇关于是产量突破相当于返回可枚举< T> .Empty从返回的IEnumerable℃的方法; T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!