Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I really like Last() and would use it all the time for List<T>s. But since it seems to be defined for IEnumerable<T>, I guess it enumerates the enumeration first - this should be O(n) as opposed to O(1) for directly indexing the last element of a List<T>.

Are the standard (Linq) extension methods aware of this?

The STL in C++ is aware of this by virtue of a whole "inheritance tree" for iterators and whatnot.

like image 488
Daren Thomas Avatar asked Sep 04 '09 08:09

Daren Thomas


People also ask

Is count faster than any?

Across the array sizes the Any is roughly 1/3 faster than using Count .

What are extension methods in LINQ?

Extension Methods are a new feature in C# 3.0, and they're simply user-made pre-defined functions. An Extension Method enables us to add methods to existing types without creating a new derived type, recompiling, or modifying the original types.

Which is better count or any?

Any() is ALWAYS faster than . Count() > 0 ).


1 Answers

I just used the Reference Source to look into the code for Last and it checks to see if it is a IList<T> 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.

like image 84
Martin Harris Avatar answered Nov 05 '22 12:11

Martin Harris