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

前端 未结 5 1864
庸人自扰
庸人自扰 2020-12-30 23:28

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

5条回答
  •  清酒与你
    2020-12-31 00:07

    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];
                }
            }
    

提交回复
热议问题