【问题标题】:Performance test [duplicate]性能测试[重复]
【发布时间】:2013-12-10 08:58:44
【问题描述】:

我正在寻找最有效的编码方式。我有一个整数或字符串列表,我需要知道该列表中的某个值是否包含在第二个集合中。

如果我对第二个集合使用字典,那么我得出了 5 种不同的搜索方式:

Dictionary<int, bool> dicSource = new Dictionary<int, bool>();
List<int> lstSearch = new List<int>();

// First approuce
var ids = dicSource.Keys.Intersect(lstSearch);
bool hasMatch1 = ids.Any();

//Second approuce
bool hasMatch2 = dicSource.Any(x => lstSearch.Any(y => y == x.Key));

//Third approuce
bool hasMatch3 = dicSource.Select(x => x.Key).Intersect(lstSearch).Any();

//Fourth approuce
bool hasMatch4 = (dicSource.Where(x => lstSearch.Contains(x.Key)).Count() > 0);

//Fifth approuce
for (int i = 0; i < lstSearch.Count; i++)
{
    bool hasMatch5 = dicSource.ContainsKey(lstSearch[i]);
}

另一方面,我可以为第二个集合使用另一个列表,然后我得出了 5 种不同的搜索方式:

List<int> lst = new List<int>();
List<int> lstIds = new List<int>();

 // First approuce
 var ids = lst.Intersect(lstIds);
 bool hasMatch1 = ids.Any();

 //Second approuce
 bool hasMatch2 = lst.Any(x => lstIds.Any(y => y == x));

 //Third approuce
 bool hasMatch3 = lst.Select(x => x).Intersect(lstIds).Any(); 

 //Fourth approuce
 bool hasMatch4 = (lst.Where(id => lstIds.Contains(id)).Count() > 0);

 //Fifth approuce
 for (int i = 0; i < lstSearch.Count; i++)
 {
     bool hasMatch5 = lstSource.Contains(lstSearch[i]);
 }

谁能告诉我这里最有效的使用方法是什么?

【问题讨论】:

标签: c# performance list dictionary


【解决方案1】:

要找出最快的,你应该进行性能测试。

但这里有另一种混合选择,可能会更快:

var lst = new HashSet<int>();
var lstIds = new HashSet<int>();

var hasMatch = lst.Intersect(lstIds).Any();

【讨论】:

  • 您将两个集合都设置为HashSet,我可以将源设置为HashSet,但另一个是List。有没有办法将 List 转换为 HashSet ?如果是的话,值得吗?
  • HashSet 有一个构造函数,它将接受一个现有的 List。
  • 酷。只是想知道,如果我使用 2 个 HashSet 或一个 HasSet 和一个 List 有区别吗?
  • 好吧,试一试!它是否对您的情况有很大影响在很大程度上取决于您的具体情况。
  • 原来列表是最有效的方法。它需要 0 毫秒...
猜你喜欢
  • 2010-10-01
  • 2010-11-01
  • 1970-01-01
  • 2014-05-23
  • 2010-10-03
  • 2021-11-15
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多