Entity Framework 5 brings many improvements and query performance improvement is one of them. In this article I'll be talking about query performances (EF1 to EF5) so that you can understand the improvements better.
Normal LINQ Query
Let's write a sample class and use a timer to get the actual time spent on query execution.
//Normal Query Method
private static void NormalQuery()
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
var myNormalQuery = from i in db.Customers
select i.Country;
foreach (var i in myNormalQuery)
{
Console.WriteLine(i);
}
}
}
And trigger it using:
Stopwatch sw = new Stopwatch();
sw.Start();
NormalQuery();
Console.WriteLine("Elapsed Time in Milliseconds : {0}", sw.ElapsedMilliseconds);
sw.Stop();
You will get output and time spent like:
Germany
Mexico
Mexico
UK
:::::::::
Elapsed Time in Milliseconds : 190
So, the total time spent was 190 milliseconds to execute a normal query. Now, go ahead and use a compiled query.
Compiled LINQ Query
Let's write a sample class and use a timer to get the actual time spent on query execution.
//Compiled Query Method
private static void CompiledQueryEF()
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
var cq = myCompiledQuery(db);
foreach (var k in cq)
{
Console.WriteLine(k);
}
}
}
//Compiled Query
private static readonly Func<DataClasses1DataContext, IEnumerable<string>> myCompiledQuery =
CompiledQuery.Compile<DataClasses1DataContext, IEnumerable<string>>(
(db) => from i in db.Customers
select i.Country);
And trigger it using:
Stopwatch sw1 = new Stopwatch();
sw1.Start();
CompiledQueryEF();
Console.WriteLine("Elapsed Time in Milliseconds : {0}", sw1.ElapsedMilliseconds);
sw1.Stop();
You will get output and time spent like:
Germany
Mexico

Gowtham RajamanickamPosted Apr 11, 2015, 1:27 PM
keep write
Gowtham RajamanickamPosted Apr 11, 2015, 1:27 PM
easy one
Abhimanyu K VatsaPosted Sep 27, 2012, 1:19 AM
yes Gaurav but only from the prospective of speed in LINQ to Object. If you go out of it, Compiled Query and now Auto-Compiled Query better.
Gaurav GuptaPosted Sep 27, 2012, 12:08 AM
Is Compiled LINQ is similar to PLINQ?