C# 是可数的<;T>;。Last()针对列表进行了优化<;T>;?
我有一个名为C# 是可数的<;T>;。Last()针对列表进行了优化<;T>;?,c#,.net,c#-4.0,C#,.net,C# 4.0,我有一个名为L的列表,包含N个项目 L.Last(),即IEnumerable扩展方法,是否将在线性时间内运行所有N项 或者它是内部优化的,以具有L[L.Count-1]的恒定时间性能?如果您查看代码如何实现Last(来自Reflector),您是对的: publicstatictsource Last(此IEnumerable源) { if(source==null) { 抛出错误。ArgumentNull(“源”); } IList list=源作为IList; 如果(列表!=null) {
L
的列表,包含N个项目
L.Last()
,即IEnumerable
扩展方法,是否将在线性时间内运行所有N项
或者它是内部优化的,以具有L[L.Count-1]
的恒定时间性能?如果您查看代码如何实现Last
(来自Reflector),您是对的:
publicstatictsource Last(此IEnumerable源)
{
if(source==null)
{
抛出错误。ArgumentNull(“源”);
}
IList list=源作为IList;
如果(列表!=null)
{
int count=list.count;
如果(计数>0)
{
返回列表[计数-1];
}
}
其他的
{
使用(IEnumerator enumerator=source.GetEnumerator())
{
if(枚举数.MoveNext())
{
t电源电流;
做
{
当前=枚举数。当前;
}
while(枚举数.MoveNext());
回流;
}
}
}
抛出错误。NoElements();
}
它实际上通过返回List[count-1]来优化List
代码>是Last
函数是循环的太妃糖包装器。内部没有魔法,即使没有在这段代码中对其进行优化,JIT编译器也可能在有足够信息的情况下对调用进行优化。有趣的是,它没有针对ICollection.Count
(给定IList:ICollection
)进行优化。让你走的东西嗯。@bradcristieICollection
没有。这正是我期望在代码中看到的。谢谢你清理它。@PKKG是一个付费应用程序,是两个免费的选择。
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();
}