Understanding the ElementAt (index) Extension

Consider this code:

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

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

As I understand it, the extension method ElementAt () has a signature

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

and since the "source" is IEnumerable, the logic executed will be similar - against what I see, which the array directly accesses.

Can someone explain this :)

+5
source share
2 answers

, . , ( is as), IList<T>. , .

- notable Count(), ICollection<T> ( .NET 4) ICollection.

, - -, "" . , : (

+5

ElementAt IEnumerable<T> , . ( O (n))

ElementAt IList<T> ( ) IList<T>, . ( O (1))

+12

All Articles