【问题标题】:HashSet replacement in C# 2.0C# 2.0 中的 HashSet 替换
【发布时间】:2011-05-12 12:12:23
【问题描述】:

我在我的项目中使用List<T>,这个列表包含数百个条目。我经常使用 List.Contains 方法,这会损害性能,我用字典替换了 List 但它导致了内存瓶颈,从而使性能变得更差。有没有更好的解决方案可以建议在列表中搜索?在 C# 2.0 中是否有 HashSet<T> 的替代品或其他在内存和速度方面都更好的方式?

【问题讨论】:

  • 你想做什么?列表约束是什么?您没有提供推荐需要基于的那种信息。
  • List 我正在使用,List.Contains 复杂度为 O(N),因此会影响性能。
  • 你在这个列表中持有什么样的数据?数百个条目通常不会那么多。无论如何,你没有解释你在用这个列表做什么。说Contains 没有任何意义。
  • 只有几百个?这会引起问题吗?除非您嵌套多个循环,否则我看不出这将是一个性能问题。
  • 你真的应该在你的问题中发布所有这些代码。

标签: c#-2.0


【解决方案1】:

Dictionary<T,bool> 可以用来代替HashSet<T>。无论您添加值为 True 还是 False 的项目都是抛硬币,该值不相关。

它比HashSet<T> 更笨重,而且不是很轻量级,但它肯定比List<T> 好。

【讨论】:

  • OP 说:I replaced the List with dictionary but it resulted in memory bottleneck
【解决方案2】:
public class HashCollection <T> : ICollection <T>
{
    private Dictionary<T, bool> _innerDictionary;

    public HashCollection()
    {
        _innerDictionary = new Dictionary<T, bool>();
    }

    void ICollection <T>.Add(T item)
    {
        AddInternal(item);
    }

    private void AddInternal(T item)
    {
        _innerDictionary.Add(item, false);
    }

    public bool Add(T item)
    {
        if (_innerDictionary.ContainsKey(item))
            return false;

        AddInternal(item);
        return true;
    }

    public void Clear()
    {
        _innerDictionary.Clear();
        _innerDictionary = new Dictionary<T, bool>();
    }

    public bool Contains(T item)
    {
        return _innerDictionary.ContainsKey(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        _innerDictionary.Keys.CopyTo(array, arrayIndex);
    }

    public int Count
    {
        get { return _innerDictionary.Keys.Count; }
    }

    public bool IsReadOnly
    {
        get
        {
            return false;
        }
    }

    public bool Remove(T item)
    {
        return _innerDictionary.Remove(item);
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _innerDictionary.Keys.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

【讨论】:

    【解决方案3】:

    如果您能够满足安装 .Net 3.5 框架的要求,您可以在 2.0 项目中使用 .Net 3.5 (System.Core.dll) 中的 HashSet。

    看到这个问题:Using HashSet in C# 2.0, compatible with 3.5

    如果不行,我会改用字典。

    【讨论】:

      猜你喜欢
      • 2012-11-07
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多