Deferred execution in C#
A lot of times, fellow developers ask me about yield return keyword and what this keyword is for.
This keyword allows us to iterate over enumerable collections in a more efficient way. Basically what does is tells the compiler do not execute this code unless is strictly necessary (for this reason it’s also called lazy evaluation).
I wrote a little sample that shows the keyword in action. The purpose of this code is to convert a DataTable into a Collection of objects. Maybe the algorithm is not the best way to accomplish the job but clearly shows how yield return works.
To see the advantages of lazy evaluation we first should take look at how the code will work if we don’t use it.
Here I convert a DataTable that contains four rows into a collection of objects and take the first element from the result. This version of convert works eagerly.
And the result is:
As we can see this in the output window, this version of the convert method walks thru the whole rows collection converting each row into an object even when we only need the first one. With a large set of data or expensive convert operation this method will perform poorly.
A better approach will be creating a method that is smart enough to not convert the whole data set when we only need the first element. This version could look something like this:
When we execute this method, we get the same result that we got before but this time we don’t walked over the whole collection of rows, when we find the first element we just stop enumerating and return the result. In this case, the second implementation performs better than the first one, saving a couple of CPU cycles and memory consumption.
This is just a sneak pick of how deferred execution works in C# and the power that LINQ brought to the .NET Framework.