Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrency or Performance Benefits of yield return over returning a 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;
}
like image 784
bendewey Avatar asked Nov 16 '08 16:11

bendewey


People also ask

Does yield return a list?

At first sight, we might think that this is a function which returns a list of 5 numbers. However, because of the yield-statement, this is actually something completely different. This method doesn't in fact return a list at all. What it does is it creates a state-machine with a promise to return 5 numbers.

What is the benefit of yield C#?

The advantage of using yield is that if the function consuming your data simply needs the first item of the collection, the rest of the items won't be created so it's more efficient. The yield operator allows the creation of items as it is demanded. That's a good reason to use it.

Does LINQ use yield?

It's more the other way around, that linq is functional in style, so it uses yield.

When should I use yield C#?

Why should I use the yield keyword? The yield keyword can do a state-full iteration sans the need of creating a temporary collection. In other words, when using the "yield return" statement inside an iterator, you need not create a temporary collection to store data before it returned.


1 Answers

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.

like image 106
Jeff Yates Avatar answered Sep 18 '22 16:09

Jeff Yates