C# .First() vs [0]

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

    Tested in LINQPad 5 with following code:

    var sw = Stopwatch.StartNew();
    for(int i = 0; i < 1000000000; i++)
    {
      List a = new List();
      a.Add(i);
      a.Add(i+2);
      int b = a.First();//[0] for B
    }
    sw.Stop();
    Console.WriteLine(sw.ElapsedTicks); 
    

    .First() gave 01:04.021 and 0:45.794 with optimization. [0] gave 0:44.288, 0:27.968 with optimization and better code for me, as I think.

    Really, for me [0] is more readable than .First() and usually I don't need checks, provided by him. So, in most cases I'll choose [0]. Thanks.

提交回复
热议问题