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 Fi
Single goes on through the whole list to make sure that there is indeed only one, so it will always hit every item in the list.
Find and First will stop as soon as they hit a match. Find is actually closer to FirstOrDefault, as Find will return the default if no match is found. First will throw an exception.
Single: https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/Single.cs
using (IEnumerator e = source.GetEnumerator())
{
while (e.MoveNext())
{
TSource result = e.Current;
if (predicate(result))
{
while (e.MoveNext())
{
if (predicate(e.Current))
{
ThrowHelper.ThrowMoreThanOneMatchException();
}
}
return result;
}
}
}
First: https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/First.cs
After some logic, it boils down to:
foreach (TSource element in source)
{
if (predicate(element))
{
found = true;
return element;
}
}
Find: https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs
for(int i = 0 ; i < _size; i++) {
if(match(_items[i])) {
return _items[i];
}
}