C#列表< T> VS IEnumerable的< T>性能问题 [英] C# List<T> vs IEnumerable<T> performance question

查看:87
本文介绍了C#列表< T> VS IEnumerable的< T>性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜猜这2种方法:

private List<IObjectProvider> GetProviderForType(Type type)
        {
            List<IObjectProvider> returnValue = new List<IObjectProvider>();

            foreach (KeyValuePair<Type, IObjectProvider> provider in _objectProviders)
            {
                if ((provider.Key.IsAssignableFrom(type) ||
                    type.IsAssignableFrom(provider.Key)) &&
                    provider.Value.SupportsType(type))
                {
                    returnValue.Add(provider.Value);
                }
            }
            return returnValue;
        }

private IEnumerable<IObjectProvider> GetProviderForType1(Type type)
        {
            foreach (KeyValuePair<Type, IObjectProvider> provider in _objectProviders)
                if ((provider.Key.IsAssignableFrom(type) ||
                    type.IsAssignableFrom(provider.Key)) &&
                    provider.Value.SupportsType(type))

                    yield return provider.Value;              
        }



哪一个是更快?当我看到第一种方法,我看到的内存分配给列表中,在我看来,它不是所需要的。在的IEnumerable 方式似乎要快给我。

例如,假设你叫

int a = GetProviderForType(myType).Count;
int b = GetProviderForType1(myType).Count();

现在,另一个问题是,是否有以上这两个之间的性能差异?

Now, another issue is, is there a performance difference between these 2 above?

你觉得呢?

推荐答案

在这种特殊情况下,使用的IEnumerable< T> 的形式会更有效率,因为你的只有的需要知道计数。有没有点中存储数据,调整缓冲区等,如果你不需要。

In this particular case, using the IEnumerable<T> 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.

如果您需要再次使用该结果以任何理由,在列表< T> 的形式会更有效。

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

请注意,无论是 COUNT()扩展方法和计数属性将是有效的列表< T> 的实施计数()检查是否目标序列实现的ICollection< T> ,并使用计数财产,如果左右。

Note that both the Count() extension method and the Count property will be efficient for List<T> as the implementation of Count() checks to see if the target sequence implements ICollection<T> 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));
}

这将避免由其中,和选择条款。

(正如马克说,对于少量的数据的性能差异可能是微不足道的反正。)

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

这篇关于C#列表&LT; T&GT; VS IEnumerable的&LT; T&GT;性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆