c# - List<T> 的 Last() 扩展方法的性能如何?

标签 c# .net linq extension-methods

我很喜欢Last()并会一直使用它 List<T>秒。但是因为它似乎是为 IEnumerable<T> 定义的,我想它首先枚举枚举——这应该是 O(n) 而不是 O(1) 直接索引 List<T> 的最后一个元素.

标准 (Linq) 扩展方法是否知道这一点?

C++ 中的 STL 通过迭代器和诸如此类的东西的整个“继承树”意识到了这一点。

最佳答案

我刚刚使用了 Reference Source查看 Last 的代码并检查它是否是 IList<T>首先执行适当的 O(1) 调用:

public static TSource Last < TSource > (this IEnumerable < TSource > source) {
    if (source == null) throw Error.ArgumentNull("source");
    IList < TSource > list = source as IList < TSource > ;
    if (list != null) {
        int count = list.Count;
        if (count > 0) return list[count - 1];
    }
    else {
        using(IEnumerator < TSource > e = source.GetEnumerator()) {
            if (e.MoveNext()) {
                TSource result;
                do {
                    result = e.Current;
                } while ( e . MoveNext ());
                return result;
            }
        }
    }
    throw Error.NoElements();
}

所以你有轻微的转换开销,但没有枚举的巨大开销。

关于c# - List<T> 的 Last() 扩展方法的性能如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1377864/

相关文章:

c# - Web API 自定义 IContractResolver

c# - 从程序集中获取类型在某些 Type.Name 的末尾添加 "' 1"

c# - .net 中的 "new "关键字实际上是做什么的?

c# - 惰性属性需要 "this"

c# - 使用 linq 返回值不为空的单元格 - Epplus

c# - 网络核心: Entity Framework ThenInclude with Projection Select

c# - 加速 LINQ 对象查询

c# - 在字典中添加字典的 int 值

c# - 加载带有大量控件的繁重 UI 的最佳方式

.net - 如何使用 NuGet 包部署 T4 包含文件