Wednesday, April 16, 2008

Deffered query execution in LINQ

LINQ improves performance by deferring the execution of the query until it is actually needed. One of the most important features of LINQ is the lazy evaluation of the query. It is this property that makes LINQ to improve performance while querying the collections.

where user.Salary > 5000 //Execute when the foreach statment is called.

selectnew { Name = user.UserName,

Salary = IncreaseSalary(user.Salary) };

foreach (var user in userSalaries)

{

Console.WriteLine(user.Name + " " + user.Salary.ToString());

}

Console.ReadKey();

}

The output of this sample is

Increasing Salary... Kemp Davis 8733

Increasing Salary... Rahul Bose 11000

Increasing Salary... Kim David 9822

By looking into the results of this execution, you will understand that the execution of the query does not happen in one time; instead it defers the execution of the query until the actual data is requested. In our example the where user.Salary > 5000 line will execute only after the actual data is requested. Here it is the foreach statement when the data is requested. This property of LINQ is called deffered execution or deffered evaluation.

When you declare a query variable, it does not actually contain the result of the query,instead it captures the data structure of the query. This data structure contains the detail about what you want to query.

It is due to thiss feature of lazy initialization LINQ improves the performance of the queries. For example when you are querying a bulk data and want to stop the query after a particular condition is met, deffered execution helps you to improve the performance by not loading the results into the memory. It will only query the collection till the condition is met!!!.

Deffered execution is the default behaviour of LINQ queries.If you want to bypass the deffered execution, you have to call the .ToList() on the query like..