如何多线程这种将所有元素添加到哈希表集合的简单操作?
foreach (var x in listx) //List of x
{
String temp1 = x.sc;
String temp2 = x.key;
Nullable<int> temp3 = x.val;
if ((null != temp2) && (string.Empty != temp2) && (int.MinValue != temp3) && "Fetch" == temp1)
{
if (false == htTempVal.ContainsKey(temp2.Trim()))
htTempVal.Add(temp2.Trim(), temp3);
}
}
只是几个快速的性能改进:
(1( 在分配 temp2 时修剪 x.Key,而不是在循环中修剪 temp2。
(2(是否可以使htTempVal成为HashSet? HashSets经过优化,允许您只添加,而不必担心检查密钥是否存在。 通过覆盖对象的 GetHashCode 并使用 HashSet,我看到了惊人的性能改进。
这些是次要的,但如果您有大约 100 万条记录,它可能会开始干扰性能。
找到一个线程安全的哈希表?
您可以先对项目进行排序,然后仅添加唯一的项目吗? 可能有一个平行排序。 然后,您可以跳过 ContainsKey(( 测试。
或者,为什么不跳过该测试,如果存在错误,则忽略错误。
最后,一百万个项目怎么会慢? 一定还有其他事情发生。
这样做,用ConcurrentDictionary
替换哈希表。但是,不能保证您会获得任何加速,因为您基本上只是在循环中进行原子操作:
ConcurrentDictionary<String, Nullable<int>> htTempVal =
new ConcurrentDictionary<String, Nullable<int>>();
Parallel.ForEach (listx,
x =>
{
String temp1 = x.sc;
String temp2 = x.key.Trim();
Nullable<int> temp3 = x.val;
if ((null != temp2) && (string.Empty != temp2) &&
(int.MinValue != temp3) && "Fetch" == temp1)
{
htTempVal.GetOrAdd(temp2, temp3);
}
});
ConcurrentDictionary.GetOrAdd
以原子方式检查并添加键值对(如果它不存在(或返回值(如果它已经在字典中((您可以忽略(。