How to you implement Deferred Execution?

Deferred execution is a technique in which the evaluation of an expression is delayed until the point where its resultant value is actually used.

Deferred execution is a technique in which the evaluation of an expression is delayed until the point where its resultant value is actually used.

This results in the resultant set not being placed in the application memory until its required, which can improve performance.

For example, the below code block loops through a collection and adds to another collection.

public IEnumerable<int> GetOdds(int upperLimit) 
{
    var oddsList = new List<int>();
    for(int i = 1; i <= upperLimit; i++) 
    {
        oddsList.Add(i);    
    }
    return oddsList;
}

foreach(var element in GetOdds(50))
{
    // the function is already executed
    // and all the odd numbers untill 50
    // are available in memory at this point
    // this is Eager Execution
}

The above code snippet returns a new List of odd numbers for a given upper limit. While the logic works, it is not so optimized in terms of performance, because we are creating a new List here and the control doesn’t come back until the entire list is processed. This is called Eager Execution.

This can have a performance hit, when dealing with a very large collection. This is where Deferred Execution helps.

In C#, deferred execution can be created by using a yield keyword, while returning a collection. The requirement is that the return type of method where yield keyword is used must be of IEnumerator or IEnumerable.

public IEnumerable<int> GetOdds(int upperLimit) 
{
    for(int i = 1; i <= upperLimit; i++) 
    {
        if(i%2 != 0) yield return i;
    }
}

foreach(var element in GetOdds(50))
{
    // for every access of element in this block
    // one single element is returned from the method
    // this saves memory, and is faster
    // this is Deferred Execution
}

The yield keyword returns one single processed object from the collection when used inside an iterator instead of the entire set. It is particularly useful when the collection is particularly huge.

Sriram Mannava
Sriram Mannava

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity.

Leave a Reply

Your email address will not be published. Required fields are marked *