What is the performance of the Last() extension method for List?

前端 未结 5 1350
慢半拍i
慢半拍i 2020-11-30 11:06

I really like Last() and would use it all the time for Lists. But since it seems to be defined for IEnumerable, I gu

5条回答
  •  孤独总比滥情好
    2020-11-30 11:26

    I just used the Reference Source to look into the code for Last and it checks to see if it is a IList first and performs the appropriate O(1) call:

    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();
    }
    

    So you have the slight overhead of a cast, but not the huge overhead of enumerating.

提交回复
热议问题