Interested, does approaches has any differences.
So, I created two snippets.
Snippet A
List a = new List();
a.Add(4);
a.Add(6);
int
The Enumerable.First method is defined as
public static TSource First(this IEnumerable source)
{
if (source == null) throw Error.ArgumentNull("source");
IList list = source as IList;
if (list != null) {
if (list.Count > 0) return list[0];
}
else {
using (IEnumerator e = source.GetEnumerator()) {
if (e.MoveNext()) return e.Current;
}
}
throw Error.NoElements();
}
So for a List
it ends up using the indexer after a null check and a cast. Seems not much, but when I tested the performance, First
was 10x slower than the indexer (for
loop, 10 000 000 iterations, release build: First - 100 ms, indexer - 10 ms).