C# .First() vs [0]

后端 未结 5 1375
遥遥无期
遥遥无期 2021-02-14 03:48

Interested, does approaches has any differences.
So, I created two snippets.

Snippet A 
List a = new List();
a.Add(4);
a.Add(6);
int         


        
5条回答
  •  情歌与酒
    2021-02-14 04:18

    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).

提交回复
热议问题