Among Find, Single, First, which one is the fastest?

As an addition to the existing answers: List.Find is much faster than IEnumerable.First because the first one can operate on the List's internal Array. The latter one has to go through the IList interface.


First will be faster than Single, because it can terminate as soon as it's found the match. On the other hand, this means it doesn't validate that only one item matched the predicate.

Find should be as fast as First, but is less portable as it will only work on lists. If you're using LINQ in general, I would try to stick to LINQ operators unless there's a definite benefit in using an alternative.

As Marc says, if you're going to do this regularly you should use a Dictionary<,>. You can use the ToDictionary operator to do this easily:

var dictionary = list.ToDictionary(x => x.Id);
// Now you can look up by ID really quickly

Obviously creating the dictionary takes some time to start with, so you'd only want to do this if you are searching multiple times.


They are different methods. Find is defined in List<T>, it's almost the same as First that is defined in Enumerable.cs as an extension method on IEnumerable<T>. Both of them will return if a conditioned item is found(no need to loop through the whole collection), so they have slight performance difference.

While Single returns the conditioned item, and also guarantees that this item is the only one that meets the condition. So in most circumstances Single is slower than First/Find because it needs to loop through the collection.


The fastest (for a large set) would be to have them keyed against a Dictionary<TKey,TValue> and use that.

Single and First do different things; Single always iterates the entire set, even if it finds it at the start of the list, so First would usually be quicker than Single since it short-circuits.

Tags:

C#