C# .First() vs [0]

后端 未结 5 1365
遥遥无期
遥遥无期 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:32

    You can check it by yourself :

        static void Main()
        {
            List resultsFirst = new List();
            List resultsIndex = new List();
    
            Stopwatch s = new Stopwatch();
    
            for (int z = 0; z < 100; z++)
            {
                List[] lists = new List[10000];
    
                int temp = 0;
    
                for (int i = 0; i < lists.Length; i++)
                    lists[i] = new List() { 4, 6 };                
    
                s.Restart();
    
                for (int i = 0; i < lists.Length; i++)
                    temp = lists[i].First();
    
                s.Stop();
    
                resultsFirst.Add(s.ElapsedTicks);
    
                s.Restart();
    
                for (int i = 0; i < lists.Length; i++)
                    temp = lists[i][0];
    
                s.Stop();
    
                resultsIndex.Add(s.ElapsedTicks);
            }
    
            Console.WriteLine("LINQ First()  :   " + resultsFirst.Average());
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("By index      :   " + resultsIndex.Average());
    
            Console.ReadKey();
        }
    

    Output in Release mode :

    LINQ First() : 367

    By index : 84

    Output in debug mode :

    LINQ First() : 401

    By index : 177

    P.S.

    The source code for method First is:

    public static TSource First(this IEnumerable source)
    {
        IList list = source as IList;
        if (list != null)
        {
            if (list.Count > 0)
            {
                return list[0];
            }
        }
        else
        {
            using (IEnumerator enumerator = source.GetEnumerator())
            {
                if (enumerator.MoveNext())
                {
                    return enumerator.Current;
                }
            }
        }
    }
    

    The casting operation source as IList or creating an Enumerator object is very likely the reason why First() is considerably slower.

提交回复
热议问题