Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between linq.first() vs array[0] [duplicate]

Tags:

c#

I am wondering what happens under the hood of list.first() and list[0] and which performs better.

For example which is faster?

for(int i = 0; i < 999999999999... i++)
{
    str.Split(';').First() vs. str.Split(';')[0]

    list.Where(x => x > 1).First() vs. list.Where(x => x > 1).ToList()[0]
}

Sorry In case of a duplicate question

like image 931
dev hedgehog Avatar asked Sep 01 '14 13:09

dev hedgehog


People also ask

Which is faster ToList or ToArray?

ToArray might do an additional allocation and copy operation such that the buffer will be sized exactly to the number of elements. In order to confirm this the following benchmark is used. The results confirm that ToList is in most cases 10% - 15% faster.

What is first () in C#?

C# Linq First() Method Use the First() method to get the first element from an array. Firstly, set an array. int[] arr = {20, 40, 60, 80 , 100}; Now, use the Queryable First() method to return the first element.

Which Linq extension retrieves the first object in a returned list or null if the list is empty?

FirstOrDefault() Returns the first element of a list with any amount of elements, or a default value if the list is empty.


1 Answers

Which performs better? The array accessor, since that doesn't need a method to be put on the stack and doesn't have to execute the First method to eventually get to the array accessor.

As the Reference Source of Enumerable shows, First() is actually:

IList<TSource> list = source as IList<TSource>;
if (list != null) {
    if (list.Count > 0) return list[0];
}

So it doesn't do anything else, it just takes more steps to get there.

For your second part (list.Where(x => x > 1).First() vs. list.Where(x => x > 1).ToList()[0]):

Where returns an IEnumerable, which isn't IList so it doesn't go for the first part of the First method but the second part:

using (IEnumerator<TSource> e = source.GetEnumerator()) {
    if (e.MoveNext()) return e.Current;
}

This will traverse each item one by one until it gets the desired index. In this case 0, so it will get there very soon. The other one calling ToList will always be less efficient since it has to create a new object and put all items in there in order to get the first one. The first call is definitely faster.

like image 101
Patrick Hofman Avatar answered Oct 14 '22 16:10

Patrick Hofman