I want to minimize the time needed to retrieve a single unique element from a list. Which one is the fastest method among Find
, Single
and First
? Note that the searching key is a unique id.
First() returns the first element of a sequence even there is a single element in that sequence. 2. Single() returns the single element of a sequence and that element should be the exactly a single one.
Single() asserts that one and only one element exists in the sequence. First() simply gives you the first one. Use Single / SingleOrDefault() when you sure there is only one record present in database or you can say if you querying on database with help of primary key of table.
Single() expects one and only one element in the collection. Single() throws an exception when it gets no element or more than one elements in the collection. If specified a condition in Single() and result contains no element or more than one elements then it throws an exception.
Single : It returns a single specific element from a collection of elements if element match found. An exception is thrown, if none or more than one match found for that element in the collection. SingleOrDefault: It returns a single specific element from a collection of elements if element match found.
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.
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.
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