Enumerable.Last< T>()和C#数组数组、Last、Enumerable、GT

2023-09-04 23:42:04 作者:渲染╰塵世的悲傷つ

说我有一个简单的数组:

Say I have a simple array:

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

这是为高性能:

Is this as performant:

double last = myDoubleArray.Last();

因为这?

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

将持续()枚举整个阵列,即使它可以使上述优化?

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

如果我通过一些其他的IEnumerable(说这就是一个产生),最后()会的有无的枚举顺序。我preFER使用最后(),因为code看起来比较清爽,但我不会做出牺牲,如果枚举的顺序。

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.

推荐答案

没有,也不会遍历各地的元素。下面是Enumerable.Last的code()的反射镜。正如你看到的,它使这种优化

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