我指的是一篇文章 http://www.albahari.com/nutshell/speedinguplinqtosql.aspx其重点是加速 LINQ to SQL 查询。它提到的技术之一是“使用编译查询”并解释了如何使用它。
我希望看到编译查询的性能改进,因此我尝试了作者提供的相同示例。我使用 Northwind Db 作为数据上下文。我尝试了正常执行和编译查询执行,并在 LINQ PAD 上检查它们。
首先我尝试执行查询without使用编译查询。花了 2.065 秒。
var oo = from o in Orders
where o.OrderDetails.Any (p => p.UnitPrice > 100)
select o;
oo.Dump ("Order items with unit price more than $100");
var oo1 = from o in Orders
where o.OrderDetails.Any (p => p.UnitPrice > 10)
select o;
oo1.Dump ("Order items with unit price more than $10");
其次,查询with使用编译查询。花了 2.100 秒。
var oo = CompiledQuery.Compile ((TypedDataContext dc, decimal unitPrice) =>
from o in Orders
where o.OrderDetails.Any (p => p.UnitPrice > unitPrice)
select o
);
oo (this, 100).Dump ("Order items with unit price more than $100");
oo (this, 10).Dump ("Order items with unit price more than $10");
重新执行几次表明这两种方法所花费的时间几乎相似。
这里我们只看到每个方法的两次查询执行。我尝试对每个问题进行 10 次查询。但两人都完成了大约7秒。
预编译查询真的能提高性能吗?或者我在使用条款上弄错了?
感谢您的时间和考虑。
Edit:阅读已接受的答案后,读者可能还想查看本文 http://www.codeproject.com/Articles/38174/How-to-improve-your-LINQ-query-performance-by-5-X这很好地解释了编译查询如何提高性能。