Greedy Operators For Eager, Not For Lazy !!!

——————————————————-
Deferred execution or Lazy execution
——————————————————-

We have seen how YIELD keyword works

One of the fundamental use of it deferred execution or lazy execution of code
We try to see this practically

class Program
{        
   static void Main(string[] args)
   {
      IEnumerable EvenNum = Extension.GetEvenNumbers();
      foreach (var item in EvenNum)
      {
          Console.WriteLine("Selected Number: {0}", item);
      }            
   }
}

public static class Extension
{
   public static IEnumerable GetEvenNumbers()
   {
      IEnumerable list = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
      foreach (var item in list)
      {
          if (item % 2 == 0)
          {
              Console.WriteLine("Start Deferred Execution");
              yield return item;
              Console.WriteLine("Stop Deferred Execution");
          }
      }
   }
}

////// OUTPUT ///////
Start Deferred Execution
Selected Number: 2
Stop Deferred Execution
Start Deferred Execution
Selected Number: 4
Stop Deferred Execution
Start Deferred Execution
Selected Number: 6
Stop Deferred Execution
Start Deferred Execution
Selected Number: 8
Stop Deferred Execution
Press any key to continue . . .

It can be seen that due to yield return in GetEvenNumbers function is not called
unless we actually required return data from function, and to do so we need to
iterate using foreach

Food For Thought:
Useful to avoid unnecessary function call which are not actually used in system by developer (:D)

—————————————————
Eager Evaluation or Execution
—————————————————

Using Greedy Operators
ToList, ToArray, ToDictionary

Product A Concrete Type
Sum, First, Single, Count

The ToList() is also eager because it transforms a collection into a concrete IEnumerable

public static List ToList(this IEnumerable source)
{
    // Arguments checking is ommitted. 
    return new List(source);
}

Inside the constructor of List, the source is iterated, and all items are calculated
and added to the List collection before it is returned.

Append ToList and this function is executed immediately

IEnumerable EvenNum = Extension.GetEvenNumbers().ToList();

/////// OUTPUT /////////
Start Deferred Execution
Stop Deferred Execution
Start Deferred Execution
Stop Deferred Execution
Start Deferred Execution
Stop Deferred Execution
Start Deferred Execution
Stop Deferred Execution
Selected Number: 2
Selected Number: 4
Selected Number: 6
Selected Number: 8
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s