views:

693

answers:

1

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;
}
+14  A: 

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.

Jeff Yates
So for small lists say under 20 items would you recommend returning just a list.
bendewey
It would depend what the elements of the list were and how much effort it took to evaluate each value. If each element in the list involved opening a 500MB file, then I'd go for the yield return approachs, if it were just a simple calculation, the list would probably be better.
Jeff Yates
+1 Great answer - thanks
Guy