C# List vs IEnumerable performance question

后端 未结 4 2162
伪装坚强ぢ
伪装坚强ぢ 2021-02-12 14:55

Hi suppose these 2 methods:

private List GetProviderForType(Type type)
        {
            List returnValue = new         


        
4条回答
  •  半阙折子戏
    2021-02-12 15:14

    In this particular case, using the IEnumerable form will be more efficient, because you only need to know the count. There's no point in storing the data, resizing buffers etc if you don't need to.

    If you needed to use the results again for any reason, the List form would be more efficient.

    Note that both the Count() extension method and the Count property will be efficient for List as the implementation of Count() checks to see if the target sequence implements ICollection and uses the Count property if so.

    Another option which should be even more efficient (though only just) would be to call the overload of Count which takes a delegate:

    private int GetProviderCount(Type type)
    {
      return _objectProviders.Count(provider =>
          (provider.Key.IsAssignableFrom(type) 
           || type.IsAssignableFrom(provider.Key))
          && provider.Value.SupportsType(type));
    }
    

    That will avoid the extra level of indirections incurred by the Where and Select clauses.

    (As Marc says, for small amounts of data the performance differences will probably be negligible anyway.)

提交回复
热议问题