【发布时间】:2010-05-05 11:07:51
【问题描述】:
我有一个 C# 应用程序,它将来自 TextFile 的数据存储在 Dictionary-Object 中。要存储的数据量可能相当大,因此插入条目需要大量时间。由于字典中的许多项目,它变得更糟,因为内部数组的大小调整,存储字典的数据。 所以我用将要添加的项目数量来初始化 Dictionary,但这对速度没有影响。
这是我的功能:
private Dictionary<IdPair, Edge> AddEdgesToExistingNodes(HashSet<NodeConnection> connections)
{
Dictionary<IdPair, Edge> resultSet = new Dictionary<IdPair, Edge>(connections.Count);
foreach (NodeConnection con in connections)
{
...
resultSet.Add(nodeIdPair, newEdge);
}
return resultSet;
}
在我的测试中,我插入了大约 30 万个项目。 我使用 ANTS Performance Profiler 检查了运行时间,发现当我使用所需大小初始化 Dictionary 时,resultSet.Add(...) 的平均时间没有改变。这和我用 new Dictionary(); 初始化 Dictionary 时一样。 (每个添加平均约 0.256 毫秒)。 这肯定是由字典中的数据量引起的(尽管我用所需的大小对其进行了初始化)。对于前 20k 项,添加的平均时间为每项 0.03 毫秒。
任何想法,如何使添加操作更快?
提前致谢, 弗兰克
这是我的 IdPair-Struct:
public struct IdPair
{
public int id1;
public int id2;
public IdPair(int oneId, int anotherId)
{
if (oneId > anotherId)
{
id1 = anotherId;
id2 = oneId;
}
else if (anotherId > oneId)
{
id1 = oneId;
id2 = anotherId;
}
else
throw new ArgumentException("The two Ids of the IdPair can't have the same value.");
}
}
【问题讨论】:
-
您是否在您的
IdPair类中覆盖Equals和GetHashCode?如果是这样,您的GetHashCode算法是否会产生良好的散列分布? -
IdPair 只是一个带有构造函数的结构。我将其添加到我的问题中
标签: c# dictionary