Concurrency or Performance Benefits of yield return over returning a list

99封情书 提交于 2019-12-03 09:55:31

In the yield return example, the result is evaluated on each call of IEnumerable.MoveNext whereas in the list example, all results are evaluated before the IEnumerable is returned (note that the Text properties may not be evaluated for each result as caching and inlining can occur). Therefore, with yield 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 to IEnumerable.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 the IEnumerable, whereas using yield return allows each element to be calculated as it is required by the consumer of the IEnumerable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!