是否对一个IList调用。去年()遍历整个列表? [英] Does calling .Last() on an IList iterate the entire list?
本文介绍了是否对一个IList调用。去年()遍历整个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请问。去年()
扩展方法考虑到,如果它被称为上的的IList
?我只是想知道是否有这之间有显著的性能差异:
Does the .Last()
extension method take into account if it's called on an IList
? I'm just wondering if there's a significant performance difference between these:
IList<int> numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int lastNumber1 = numbers.Last();
int lastNumber2 = numbers[numbers.Count-1];
直觉告诉我,第一选择是O(n),但第二个是O(1)。为。去年()
聪明,足以尝试转换为一个的IList
?
Intuition tells me that the first alternative is O(n) but the second is O(1). Is .Last()
"smart" enough to try casting it to an IList
?
推荐答案
大概不会,因为它可以做列表[list.count-1]
Probably not, as it can do list[list.count-1]
通过反射验证:
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];
}
}
...
}
这篇关于是否对一个IList调用。去年()遍历整个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文