是产量突破相当于返回可枚举< T> .Empty从返回的IEnumerable℃的方法; T> [英] Is yield break equivalent to returning Enumerable<T>.Empty from a method returning IEnumerable<T>

查看:131
本文介绍了是产量突破相当于返回可枚举< T> .Empty从返回的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.

这篇关于是产量突破相当于返回可枚举&LT; T&GT; .Empty从返回的IEnumerable℃的方法; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆