Lazy Evaluation Example Fibonacci Numbers

suggest change
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics; // also add a reference to System.Numerics

namespace ConsoleApplication33
{
    class Program
    {
        private static IEnumerable<BigInteger> Fibonacci()
        {
            BigInteger prev = 0;
            BigInteger current = 1;
            while (true)
            {
                yield return current;
                var next = prev + current;
                prev = current;
                current = next;
            }
        }

        static void Main()
        {
            // print Fibonacci numbers from 10001 to 10010
            var numbers = Fibonacci().Skip(10000).Take(10).ToArray();
            Console.WriteLine(string.Join(Environment.NewLine, numbers));
        }
    }
}

How it works under the hood (decompile the resulting .exe with the IL Disassembler, ildasm):

  1. C# compiler generates a class implementing IEnumerable<BigInteger> and IEnumerator<BigInteger> (<Fibonacci>d__0 in ildasm).
  2. This class implements a state machine. State consists of current position in method and values of local variables.
  3. The most interesting code is in bool IEnumerator.MoveNext(). Basically, what MoveNext() does:

Also note that the 10001st number is 6942 bits, about 868 bytes as a BigInteger. State machine only saves current and prev variables as fields. While if we would like to save all numbers in the sequence from the first to the 10000th, the consumed memory size will be over 4 megabytes. So lazy evaluation, if properly used, can reduce memory footprint in some cases.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents