針對 LINQ to SQL 性能質疑,以 Northwind Products 表(3000 行)為例,測試主鍵單行查詢 3000 次。
| 方式 | 耗時 | 備註 |
|---|---|---|
| SqlDataReader (手寫 SQL) | 0.65 秒 | 基準線 |
| LINQ to SQL (原始 Lambda) | 21.2 秒 | 每次構建 Expression 樹 |
| LINQ to SQL (共享連接) | ~21 秒 | 連接池使優化無效 |
| LINQ to SQL (CompiledQuery) | ~1 秒 | 預編譯查詢計劃 |
// 原始:每次查詢重新構建表達式樹
var product = ctx.Products.Single(p => p.ProductID == i);
// 優化:預編譯
var query = CompiledQuery.Compile((NorthwindDataContext nw, int id) =>
nw.Products.Single(p => p.ProductID == id));
// 循環中調用
for (int i = 1; i <= 3000; i++)
var product = query(ctx, i);
Expression 與 Func 開銷極大,CompiledQuery 必須用於熱路徑。感謝社區網友 jyk、Adrian、jjx 指出 Lambda 表達式開銷問題,驗證 CompiledQuery 效果顯著。