by Dominic Zukiewicz
31. March 2008 15:33
Updated: This article is 2 of
the 2 posts about this problem (Problem AND Solution)
The answer to this is definitely ... NO!
When a colleague looked over my example, we shared some ideas about what LINQ is actually doing.
It turns out that my LINQ version was working faster because
it wasn't actually doing anything!
By design, LINQ defers all processing until the data is actually used. Being assigned as it was wasn't enough!
var q = from c in db.Customers
where c.City == "London"
select c;
This only prepares the query, but no execution is carried out. So in order for the query to take place, one of its values have to be queried. I achieved this with:
foreach(Customer c in q)
break;
This forces the GetEnumerator() to fire, causing LINQ to get the results. Now the results are coming back, and we can see for sure that LINQ is
SLOWER than CompiledQuery().
My statistics aren't as accurate as my previous post due to me running more processes on it (whereas
Part 1 was left running on its own), but you can still see the difference in speed:
Timings for each method
| Iterations |
Normal |
Compiled |
Notes |
| |
Total Query Time (s) |
Total Query Time (s) |
|
| 100 |
0.4531 |
0.1094 |
75.9 % quicker |
| 1000 |
1.5469 |
1.0313 |
33.3 % quicker |
| 5000 |
8.4844 |
5.7188 |
32.6 % quicker |
| 10000 |
16.0000 |
9.7969 |
38.8 % quicker |
| 50000 |
78.4844 |
52.2500 |
33.4 % quicker |
| 100000 |
163.9688 |
99.1875 |
39.5 % quicker |
| 500000 |
763.2500 |
470.2031 |
38.4 % quicker |
| 1000000 |
1498.2656 |
981.9844 |
34.5 % quicker |
ab493d5c-af3f-468c-bdfa-02d2a510e81e|0|.0
Tags:
.NET 3.5