什么是名单,其中最后的()扩展方法的性能; T>? [英] What is the performance of the Last() extension method for List<T>?

查看:251
本文介绍了什么是名单,其中最后的()扩展方法的性能; T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很喜欢末()键,会使用它所有的时间名单,其中,T> 秒。但是,因为它似乎为的IEnumerable&LT被定义; T> ,我想这枚举枚举第一 - 这应该是为O(n),而不是O(1)直接索引的最后一个元素名单,其中,T>

I really like Last() and would use it all the time for List<T>s. But since it seems to be defined for IEnumerable<T>, I guess it enumerates the enumeration first - this should be O(n) as opposed to O(1) for directly indexing the last element of a List<T>.

是标准的(LINQ)扩展方法意识到这一点?

Are the standard (Linq) extension methods aware of this?

在C ++ STL是意识到这一点凭借整体继承树的迭代器和诸如此类的东西。

The STL in C++ is aware of this by virtue of a whole "inheritance tree" for iterators and whatnot.

推荐答案

我只是用反光寻找到了$ C $下最后它检查,看它是否是一个的IList&LT; T&GT; 第一,并执行相应的O(1)电话:

I just used reflector to look into the code for Last and it checks to see if it is a IList<T> first and performs the appropriate O(1) call:


编辑:

在我的律师的意见,我已删除从反射镜中的code段。如果你想看到的code为自己,我建议你要么反射,并自己动手(应该已经使得每个人),或者更简单地看在这个职位的修订历史记录(因为没有什么我可以做的)

On the advice of my lawyer I have removed the code snippet from reflector. If you want to see the code for yourself I suggest you either get Reflector and do it yourself (which everyone should have already) or more simply look in the revision history of this post (since there is nothing I can do about that)

(或实际上看马克的回答谁显然不具有相同的裂纹法律团队保护他)

(Or indeed look at Mark's answer who clearly doesn't have the same crack legal team protecting him)


所以,你有一个投少量的开销,但没有列举的巨大的开销。

So you have the slight overhead of a cast, but not the huge overhead of enumerating.

这篇关于什么是名单,其中最后的()扩展方法的性能; T&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆