c# - 在 IList 上调用 .Last() 是否会迭代整个列表?

标签 c#

<分区>

.Last() 扩展方法是否考虑在 IList 上调用?我只是想知道它们之间是否存在显着的性能差异:

IList<int> numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

int lastNumber1 = numbers.Last();
int lastNumber2 = numbers[numbers.Count-1];

直觉告诉我,第一个备选方案是 O(n),而第二个是 O(1)。 .Last() 是否“聪明”到足以尝试将其转换为 IList

最佳答案

可能不会,因为它可以做到 list[list.count-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];
        }
    }
    ...
}

关于c# - 在 IList 上调用 .Last() 是否会迭代整个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4833220/

相关文章:

c# - 如何在 C# 中将数字转换为 dd/mm/yyyy 格式?

c# - 使用 YouTube API v3 上传字幕(dotnet、C#、空错误、挑战)

c# - 如何使 MySql 和 EF Core 将 tinyint 或 bit 映射到 bool 值?

c# - sqlParameters vs string.Format 哪个更能提高速度?

c# - 什么允许匿名无参数委托(delegate)类型有所不同?

c# - SQL DELETE(级联 DELETE 与 TRIGGERS 与 "Manual"-DELETE)

c# - 随时间移动游戏对象

C#:我无法从 do-loop 中的列表访问信息

c# - 使用 fsutil hardlink create 而不是缓慢的复制任务来加速 msbuild

c# - 拥有一个大的工作流程还是几个更小的具体工作流程更好?