Wednesday, June 19, 2013

.NET Developer Interview Question: What is Deferred Execution?

According to MSDN definition, "Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required". The main benefit of using deferred execution is that it can greatly improve performance when you have to manipulate large data collections, especially in programs that contain a series of chained queries or manipulations.


In .NET and Microsoft technologies, C# is supporting deferred execution via using yield keyword (LINQ extensively uses deferred execution as one way of executing its queries).


C# Example:
public class Program
{
    static void Main()
    {
       foreach (int value in ComputePower(2, 30))
       {
          Console.Write(value);
       }
    }

    public static IEnumerable ComputePower(int number, int exponent)
    {
       int exponentNum = 0;
       int numberResult = 1;
  
       // Continue loop until the exponent count is reached.
       while (exponentNum < exponent)
       {
          numberResult *= number;
          exponentNum++;
     
          yield return numberResult;
       }
    }
}

In the above example, the computation of the 2 power 30 will be deffered to where the for-each looped value is used, which will boost up the performance of this chunk of code.


 LINQ Example:
class Program
{
    static void Main(string[] args)
    {
        string[] stringArray = { "abc", "def", "ghi" };

        var q = from str in stringArray.ConvertCollectionToUpperCase()
                select str;

        foreach (string str in q)
            Console.WriteLine("Main: str {0}", str);
    }
    
    public static IEnumerable 
                   ConvertCollectionToUpperCase(this IEnumerable source)
    {
        foreach (string str in source)
        {
            Console.WriteLine("ToUpper: source {0}", str);
            yield return str.ToUpper();
        }
    }
}

In the above example, the same happens with the LINQ queries. Once you use the value of str in the for-each loop, result of ConvertCollectionToUpperCase will be executed. 

No comments:

Post a Comment