Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .First() vs [0]

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

Snippet A 
List<int> a = new List<int>();
a.Add(4);
a.Add(6);
int b = a.First(); 

and

Snippet B 
List<int> a = new List<int>();
a.Add(4);
a.Add(6);
int b = a[0]; 

In IL we trust, so

Snippet A IL
IL_0000:  nop         
IL_0001:  newobj      System.Collections.Generic.List<System.Int32>..ctor
IL_0006:  stloc.0     // a
IL_0007:  ldloc.0     // a
IL_0008:  ldc.i4.4    
IL_0009:  callvirt    System.Collections.Generic.List<System.Int32>.Add
IL_000E:  nop         
IL_000F:  ldloc.0     // a
IL_0010:  ldc.i4.6    
IL_0011:  callvirt    System.Collections.Generic.List<System.Int32>.Add
IL_0016:  nop         
IL_0017:  ldloc.0     // a
IL_0018:  call        System.Linq.Enumerable.First
IL_001D:  stloc.1     // b
IL_001E:  ret        

and

Snippet B IL
IL_0000:  nop         
IL_0001:  newobj      System.Collections.Generic.List<System.Int32>..ctor
IL_0006:  stloc.0     // a
IL_0007:  ldloc.0     // a
IL_0008:  ldc.i4.4    
IL_0009:  callvirt    System.Collections.Generic.List<System.Int32>.Add
IL_000E:  nop         
IL_000F:  ldloc.0     // a
IL_0010:  ldc.i4.6    
IL_0011:  callvirt    System.Collections.Generic.List<System.Int32>.Add
IL_0016:  nop         
IL_0017:  ldloc.0     // a
IL_0018:  ldc.i4.0    
IL_0019:  callvirt    System.Collections.Generic.List<System.Int32>.get_Item
IL_001E:  stloc.1     // b
IL_001F:  ret  

Snippet B produced one command more IL, but which approach faster in the end?

like image 457
Arman Hayots Avatar asked Nov 05 '15 12:11

Arman Hayots


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


1 Answers

You could check it by yourself :

    static void Main()
    {
        List<long> resultsFirst = new List<long>();
        List<long> resultsIndex = new List<long>();

        Stopwatch s = new Stopwatch();

        for (int z = 0; z < 100; z++)
        {
            List<int>[] lists = new List<int>[10000];

            int temp = 0;

            for (int i = 0; i < lists.Length; i++)
                lists[i] = new List<int>() { 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<TSource>(this IEnumerable<TSource> source)
{
    IList<TSource> list = source as IList<TSource>;
    if (list != null)
    {
        if (list.Count > 0)
        {
            return list[0];
        }
    }
    else
    {
        using (IEnumerator<TSource> enumerator = source.GetEnumerator())
        {
            if (enumerator.MoveNext())
            {
                return enumerator.Current;
            }
        }
    }
}

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

P.S.

With that in mind I wouldn't recommend always using indexer as it might produce a less readable code at times. Usually readability is more important than micro optimizations.

For example:

var lastEmployee = employees[employees.Count - 1]; // and even
var lastEmployee = employees[^1];                  // C#8

is less readable than:

var lastEmployee = employees.Last();
like image 152
Fabjan Avatar answered Sep 21 '22 17:09

Fabjan