收益率返回相对于返回列表的并发性或性能优势
我想知道使用yield return 相对于返回列表是否有任何并发性(现在或将来)或性能优势。 请参阅以下示例
处理方法
void Page_Load()
{
foreach(var item in GetPostedItems())
Process(item);
}
使用yield return
IEnumerable<string> GetPostedItems()
{
yield return Item1.Text;
yield return Item2.Text;
yield return Item3.Text;
}
返回列表的
IEnumerable<string> GetPostedItems()
{
var list = new List<string>();
list.Add(Item1.Text);
list.Add(Item2.Text);
list.Add(Item3.Text);
return list;
}
I was wondering if there is any concurrency (now or future), or performance benefit to using yield return over returning a list. See the following examples
Processing Method
void Page_Load()
{
foreach(var item in GetPostedItems())
Process(item);
}
using yield return
IEnumerable<string> GetPostedItems()
{
yield return Item1.Text;
yield return Item2.Text;
yield return Item3.Text;
}
returning a list
IEnumerable<string> GetPostedItems()
{
var list = new List<string>();
list.Add(Item1.Text);
list.Add(Item2.Text);
list.Add(Item3.Text);
return list;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
yield return
示例中,每次调用IEnumerable.MoveNext
时都会评估结果,而在列表示例中,所有结果都会在IEnumerable
之前评估> 返回(请注意,可能不会对每个结果评估Text
属性,因为可能会发生缓存和内联)。 因此,使用yield return
,您应该在第一次调用枚举器时获得小幅性能增强,然后在每次后续调用IEnumerable.MoveNext
时可能会出现小幅性能下降,因为财产被评估。yield return
的一大优点是,您可以返回无限序列、随机序列和各种其他新颖的枚举,这些枚举要么效率极低,要么无法通过创建列表的模型来完成第一的。简而言之,返回
List
实例需要在返回IEnumerable
之前评估列表中的所有元素,而使用yield return
允许按照IEnumerable
使用者的要求计算每个元素。In the
yield return
example, the result is evaluated on each call ofIEnumerable.MoveNext
whereas in the list example, all results are evaluated before theIEnumerable
is returned (note that theText
properties may not be evaluated for each result as caching and inlining can occur). Therefore, withyield return
you should get a small performance enhancement on the first call to the enumerator and then potentially a small performance decrease on each subsequent call toIEnumerable.MoveNext
as the property is evaluated.One of the great things about
yield return
is that you can return infinite sequences, random sequences, and all sorts of other novel enumerations that would either be extremely inefficient or impossible to do with the model of creating a list first.To put it simply, returning an instance of
List
requires that all elements in the list are evaluated prior to returning theIEnumerable
, whereas usingyield return
allows each element to be calculated as it is required by the consumer of theIEnumerable
.