了解扩展ElementAt(index) [英] Understanding the extension ElementAt(index)

查看:108
本文介绍了了解扩展ElementAt(index)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

int size = 100 * 1000 * 1000;
var emu = Enumerable.Range(0, size);
var arr = Enumerable.Range(0, size).ToArray();

当我调用emu.ElementAt(size-10)和arr.ElementAt(size-10)并测量arr的时间快得多时(数组为0.0002s,而IEnumerable为0.59s).

when I call emu.ElementAt(size-10) and arr.ElementAt(size-10) and measure the time the arr is much faster (the array is 0.0002s compared to IEnumerable 0.59s).

据我所知,扩展方法ElementAt()具有签名

As I understand it, the extention method ElementAt() have the signature

public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index)

并且由于源"是IEnumerable,因此执行的逻辑将是相似的-与我所看到的直接访问数组的位置相反.

and since the 'source' is a IEnumerable the logic carried out would be similar - opposed to what I see where the array is accessed directly.

有人可以解释一下吗:)

Could someone please explain this :)

推荐答案

这是在执行时间进行的优化.尽管该调用没有过载,但是它能够(使用isas)检查该源是否实际上是IList<T>.如果是这样,则可以直接转到正确的元素.

This is an optimization performed at execution-time. Although the call isn't overloaded, it is able to check (using is or as) whether the source is actually an IList<T>. If it is, it's able to go directly to the right element.

各种其他调用也可以做到这一点-值得注意的Count()已针对ICollection<T>和非通用ICollection接口进行了优化(从.NET 4开始).

Various other calls do this - notable Count() which is optimised for ICollection<T> and (as of .NET 4) the nongeneric ICollection interface.

扩展方法的缺点之一是所有这些优化都必须由实现本身执行-类型不能覆盖任何内容以选择加入"优化扩展方法.这意味着优化必须由原始实现者全部了解:(

One of the downsides of extension methods is that all these optimizations have to be performed by the implementation itself - types can't override anything to "opt in" to optimizing extension methods. That means the optimizations have to all be known by the original implementor :(

这篇关于了解扩展ElementAt(index)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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