Is there a performance boost by using yield with foreach?

After reading a few articles : http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx

There is one thing that I didn't quite understand and was curious about.

I was curious to know a foreach loop can utilize yielded function's results before all the yields have been completed.

Take the follow functions for example:

    public static IEnumerable<int> RandomFunction()
    {
        for (int i = 0; i < int.MaxValue; i++)
            yield return i; 
    }

    public static void PrintRandomResult1()
    {
        foreach (var i in RandomFunction())
            Console.WriteLine(i);
    }

    public static void PrintRandomResult2()
    {
        IEnumerable<int> Enumerable = RandomFunction();
        foreach(var i in Enumerable)
            Console.WriteLine(i);
    }

If we use PrintRandomResult2 I would assume the Randomfunction would have reached all of its yields before the foreach beings; however, if we call the RandomFunction directly in the foreach will the iterations begin before RandomFunction is complete?

Jon Skeet
people
quotationmark

I was curious to know a foreach loop can utilize yielded function's results before all the yields have been completed.

Absolutely, that's part of the point. The iterator block executes lazily.

The method effectively "pauses" when it hits a yield return - then continues next time the foreach loop implicitly calls MoveNext(). It doesn't just run through the whole code and build up a list to return at the end, if that's what you were speculating.

From the MSDN page you linked to:

When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

EDIT: You've linked to my implementation article - the more introductory article might help you, as that gives a worked example.

people

See more on this question at Stackoverflow