Is IEnumerable<T>.Last() optimized for List<T>?
.net, c#, c#-4.0
Solution
You are right, if you take a look the code how to implement `Last` (from Reflector):
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> enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
TSource current;
do
{
current = enumerator.Current;
}
while (enumerator.MoveNext());
return current;
}
}
}
throw Error.NoElements();
}
It actually optimizes for `List<T>` by returning `list[count - 1];`
Problem
I have a `List<T>`, called `L`, containing N items. Is `L.Last()`, the `IEnumerable<T>` extension method, going to run through all N items in linear-time? Or is it internally optimized to have the constant-time performance of `L[L.Count - 1]`?