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.
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!
FirstOrDefault<TSource>(IEnumerable<TSource>) Returns the first element of a sequence, or a default value if the sequence contains no elements.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With