我試圖在LINQ to SQL(WP7,C#和SQLCE 3.5數據庫)中使用CompiledQuery
,但在第一次使用後,查詢速度減慢到未編譯速度。我是新手,我確信我錯過了一些明顯的東西,但我不確定是什麼。LINQ to SQL編譯查詢減速
作爲上下文,我有一個相當大的術語數據庫(大約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來檢查實際的數據庫查詢,以瞭解它爲什麼如此緩慢。 – st78 2012-04-25 16:13:21
謝謝謝爾蓋,你絕對是對的! – Superangel 2012-04-25 22:33:01