且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

LINQ 方法的运行时复杂度 (Big-O) 有哪些保证?

更新时间:2023-01-15 15:28:07

有非常非常少的保证,但有一些优化:

There are very, very few guarantees, but there are a few optimizations:

  • 使用索引访问的扩展方法,例如 ElementAtSkipLastLastOrDefault, 将检查底层类型是否实现了 IList,以便您获得 O(1) 访问而不是 O(N).

  • Extension methods that use indexed access, such as ElementAt, Skip, Last or LastOrDefault, will check to see whether or not the underlying type implements IList<T>, so that you get O(1) access instead of O(N).

Count 方法检查 ICollection 实现,因此该操作是 O(1) 而不是 O(N).

The Count method checks for an ICollection implementation, so that this operation is O(1) instead of O(N).

DistinctGroupBy Join,我也相信集合聚合方法(Union, IntersectExcept) 使用散列,所以它们应该接近 O(N) 而不是 O(N²).

Distinct, GroupBy Join, and I believe also the set-aggregation methods (Union, Intersect and Except) use hashing, so they should be close to O(N) instead of O(N²).

Contains 检查 ICollection 实现,所以如果底层集合也是 O(1),例如HashSet,但这取决于实际的数据结构,并不能保证.哈希集覆盖了 Contains 方法,这就是为什么它们是 O(1).

Contains checks for an ICollection implementation, so it may be O(1) if the underlying collection is also O(1), such as a HashSet<T>, but this is depends on the actual data structure and is not guaranteed. Hash sets override the Contains method, that's why they are O(1).

OrderBy 方法使用稳定的快速排序,因此它们是 O(N log N) 平均情况.

OrderBy methods use a stable quicksort, so they're O(N log N) average case.

我认为这涵盖了大部分(如果不是全部)内置扩展方法.真的很少有性能保证;Linq 本身会尝试利用高效的数据结构,但编写潜在的低效代码并不是免费的.

I think that covers most if not all of the built-in extension methods. There really are very few performance guarantees; Linq itself will try to take advantage of efficient data structures but it isn't a free pass to write potentially inefficient code.