jon*_*ers 15 .net c# linq arrays ienumerable
说我有一个简单的数组:
double[] myDoubleArray = new double[] { 0, 1, 2, 3, 4, 5 };
Run Code Online (Sandbox Code Playgroud)
这是性能如何:
double last = myDoubleArray.Last();
Run Code Online (Sandbox Code Playgroud)
这个?
double last = myDoubleArray[myDoubleArray.Length - 1];
Run Code Online (Sandbox Code Playgroud)
即使可以进行上述优化,Last Last()会枚举整个数组吗?
如果我传递了一些其他的IEnumerable(比如一个已经产生的),Last()必须枚举序列.我更喜欢使用Last(),因为代码看起来更干净,但如果它枚举序列我就不会做出牺牲.
arc*_*hil 23
不,它不会迭代所有元素.这是来自反射器的Enumerable.Last()的代码.如你所见,它进行了这样的优化
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();
}
Run Code Online (Sandbox Code Playgroud)
不,Last 没有谓词优化IList<T>案例,包括一维数组.
使用谓词,它不执行优化.特别是,它不会从最后向后工作(由于例外可能会改变结果).
直接访问最后一个元素仍然会稍微快一些,但是Last()更具可读性并且只是"恒定时间"不同 - 在这种情况下它不会将O(1)操作更改为O(N).
有关更多信息Last,请参阅我的Edulinq博客文章.
请注意,优化没有记录,所以可以说你不应该依赖它.在实践中,我无法想象它会变成O(N):)