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
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.
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.
FirstOrDefault() Returns the first element of a list with any amount of elements, or a default value if the list is empty.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With