Why is OfType<> faster than Cast<>?

后端 未结 4 1923
猫巷女王i
猫巷女王i 2020-12-15 03:39

In answer to the following question: How to convert MatchCollection to string array

Given The two Linq expressions:

var arr = Regex.Matches(strText,          


        
4条回答
  •  一生所求
    2020-12-15 04:25

    OfType() should be slower since doing safe type is check before an actual explicit cast operation, in the same time Cast() doing only explicit cast.

    Theoretically OfType woudl be faster in case of many elements with "wrong type", so loop enumerates further just after is check, in case of Cast() on the same collection you would end's up with an InvalidCastException on each element of "wrong type" so this would be relatively slower.

    Source code extracted using ILSpy:

    // System.Linq.Enumerable
    private static IEnumerable OfType(IEnumerable source)
    {
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
    
        foreach (object current in source)
        {
            // **Type check**
            if (current is TResult)
            {
                // **Explicit cast**
                yield return (TResult)current;
            }
        }
        yield break;
    }
    
    // System.Linq.Enumerable
    public static IEnumerable Cast(this IEnumerable source)
    {
        IEnumerable enumerable = source as IEnumerable;
        if (enumerable != null)
        {
            return enumerable;
        }
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
    
        foreach (object current in source)
        {
            // **Explicit cast only**
            yield return (TResult)current;
        }
        yield break;
    }
    

提交回复
热议问题