【发布时间】:2012-04-25 10:01:23
【问题描述】:
我正在尝试在 LINQ to SQL(WP7、C# 和 SQLCE 3.5 数据库)中使用 CompiledQuery,但在第一次使用后,查询速度会降低到未编译的速度。我是新手,我确定我错过了一些明显的东西,但我不确定是什么。
作为上下文,我有一个相当大的术语数据库(大约 100,000 条记录),我想搜索这个数据库。在尝试了各种不同的方法和优化之后,我的查询仍然很慢,因此我考虑使用CompileQuery。
以下是我在 LINQPad 中拼凑的一些代码:
// A list of search terms
List<string> keywords = new List<string>()
{
"almond",
"banana",
"chocolate",
"date",
"elderberry",
};
// Searches for each keyword in the database
void Main()
{
int i = 0;
while (i < keywords.Count)
{
Stopwatch timer = Stopwatch.StartNew();
IQueryable<Result> r = CQ(this, keywords[i]);
timer.Stop();
Console.WriteLine("Query: {0}\nTime: {1}ms\n",
query,
timer.ElapsedMilliseconds);
i++;
}
}
// The compiled query property
static Func<TypedDataContext, string, IQueryable<Result>> CQ
{
get
{
return CompiledQuery.Compile<TypedDataContext, string, IQueryable<Result>>
(
(TypedDataContext dc, string query) =>
(
from x in dc.MyTable
where x.MyColumn.Contains(query)
select new Result
{
Something = x.MyColumn
}
)
);
}
}
// A simple class to hold the results
class Result
{
public string Something { get; set; }
}
当然,这过于简化了,但你明白了。现在产生的结果是:
Query: almond
Time: 14ms
Query: banana
Time: 1197ms
Query: chocolate
Time: 1191ms
Query: date
Time: 1226ms
Query: elderberry
Time: 1201ms
大家都说第一次查询会比较慢,但是后面的查询会比较快。但是在我的情况下,情况正好相反:看起来第一个查询已编译,但后面的查询未编译。
我确定这很明显,但我不确定我错过了什么。有什么指点吗?
非常感谢!
【问题讨论】:
-
我认为无论如何编译时间都小于 0.01 秒。这不应该是一个理由。我建议使用 sql profiler 检查实际的数据库查询,以找出它如此慢的原因。
-
谢谢谢尔盖,你说得对!
标签: c# linq-to-sql sql-server-ce compiled-query