Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerable.Last<T>() and C# arrays

Say I have a simple array:

double[] myDoubleArray = new double[] { 0, 1, 2, 3, 4, 5 };

Is this as performant:

double last = myDoubleArray.Last();

as this?

double last = myDoubleArray[myDoubleArray.Length - 1];

Will Last() enumerate over the entire array even when it can make the above optimization?

If I passed some other IEnumerable (say one that was yielded), Last() would have to enumerate the sequence. I prefer using Last(), because code looks cleaner, but I would not make a sacrifice if it enumerates the sequence.

like image 812
jonathanpeppers Avatar asked Apr 08 '11 13:04

jonathanpeppers


People also ask

What is IEnumerable T in C#?

Background Topics - IEnumerable<T> That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!

What is FirstOrDefault C#?

FirstOrDefault<TSource>(IEnumerable<TSource>) Returns the first element of a sequence, or a default value if the sequence contains no elements.

What is Linq enumerable?

Returns the number of elements in a sequence. Returns a number that represents how many elements in the specified sequence satisfy a condition. Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty.


1 Answers

No, it won't iterate all over elements. Here's the code of Enumerable.Last() from reflector. As you see, it makes such optimization

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();
}
like image 108
archil Avatar answered Sep 27 '22 18:09

archil