对 EF-to-Linq 查询进行排序的最快方法是什么?

What is the fastest way to sort an EF-to-Linq query?

使用Entity Framework,理论上哪个更快:

// (1) sort then select/project
// in db, for entire table
var results = someQuery
              .OrderBy(q => q.FieldA)
              .Select(q => new { q.FieldA, q.FieldB })
              .ToDictionary(q => q.FieldA, q => q.FieldB);

// (2) select/project then sort
// in db, on a smaller data set
var results = someQuery
              .Select(q => new { q.FieldA, q.FieldB })
              .OrderBy(q => q.FieldA)
              .ToDictionary(q => q.FieldA, q => q.FieldB);

// (3) select/project then materialize then sort
// in object space
var results = someQuery
              .Select(q => new { q.FieldA, q.FieldB })
              .ToDictionary(q => q.FieldA, q => q.FieldB)
              .OrderBy(q => q.FieldA);  // -> this won't compile, but you get the question

我不是 SQL 专家,但直觉上似乎 2 比 1 快...对吗?这与 3 相比如何,因为根据我使用 EF 的经验,在数据库上完成几乎所有事情都更快。

PS 我的环境中没有 perf 工具,不确定如何测试它,因此出现了这个问题。

您的查询在您调用 ToDictionary 时正在编译和执行,因此 1 和 2 应该相同并产生相同的查询:在这两种情况下您都会得到 SELECT FieldA, FieldB FROM table ORDER BY FieldA

第三种不同:您首先执行 SQL 查询(没有 ORDER BY 子句),然后对返回的内存中的集合进行排序(数据不是由 DB 提供程序排序,而是由客户)。这可能会更快或更慢,具体取决于数据量、服务器和客户端的硬件、数据库的设计方式(索引等)、网络基础设施等。

根据您提供的信息无法判断哪个更快

PS:这没有意义,因为 Dictionary 并不真正关心顺序(我不认为 3 会编译,因为 Dictionary<>,如果我不是弄错了,没有 OrderBy),但将 ToDictionary 更改为 ToList,这就是你的表现答案