Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 443
xport Avatar asked Jan 27 '11 07:01

xport


People also ask

What is the difference between First and Single?

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.

When to use Single and First in LINQ?

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.

How to use Single in c#?

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.

What is difference between single and SingleOrDefault?

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.


2 Answers

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.

like image 159
Marc Gravell Avatar answered Nov 15 '22 17:11

Marc Gravell


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.

like image 38
Jon Skeet Avatar answered Nov 15 '22 19:11

Jon Skeet