High runtime for Dictionary.Add for lots of items

I have a C # -Application that stores data from a TextFile into a Dictionary-Object. The amount of data that needs to be saved can be quite large, so it takes a long time to insert records. With many items in the Dictionary, this gets even worse due to the resizing of the internal array that stores the data for the Dictionary. Therefore, I initialized the dictionary with the number of elements to be added, but this does not affect the speed.

Here is my function:

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;
}

~ 300 . ANTI Performance Profiler , resultSet.Add(...) . , (); ( 0,246 ). (ALTHOUGH ). 20 . 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.");
  }
}
+5
2

, Equals() GetHashCode(). , , , , .

, - GetHashCode(), , , XOR ( hash (a, b) == hash (b, a)). , ValueType.GetHashCode() ,

public override int GetHashCode() {
    return oneId << 16 | (anotherId & 0xffff);
}

.

+9

IdPair struct, Equals GetHashCode. , .

Equals GetHashCode , . , .

, , /:

public struct IdPair : IEquatable<IdPair>
{
    // ...

    public override bool Equals(object obj)
    {
        if (obj is IdPair)
            return Equals((IdPair)obj);

        return false;
    }

    public bool Equals(IdPair other)
    {
        return id1.Equals(other.id1)
            && id2.Equals(other.id2);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 269;
            hash = (hash * 19) + id1.GetHashCode();
            hash = (hash * 19) + id2.GetHashCode();
            return hash;
        }
    }
}
+7

All Articles